Lua math.random() 总是返回相同的数字?

我想要一个字符串包含0或1来完成某个项目。 所以我尝试了这个

local data = ""
for i=1, 5 do
    data = data .. math.random(2) - 1
end
print(data)

这个程序总是返回10111作为结果。所以在搜索后我找到了一个类似的问题。[链接](https://stackoverflow.com/questions/52745798/lua-random-number-generator-always-produces-the-same-number) 所以我按照那个程序更改了我的程序

local data = ""
for i=1, 5 do
    math.randomseed(os.time())
    data = data .. math.random(2) - 1
end
print(data)

还有这个

local data = ""
for i=1, 5 do
    math.randomseed(os.time())
    math.random(2)
    math.random(2)
    math.random(2)
    data = data .. math.random(2) - 1
end
print(data)

所以当我尝试这个程序时,它总是以1111100000作为输出。为什么? 如何才能正确地获得随机的0或1在我的字符串中??

原文链接 https://stackoverflow.com/questions/70508610

点赞
stackoverflow用户1837006
stackoverflow用户1837006

在循环之前添加种子:

local data = ""
math.randomseed(os.time())  -- 在这里添加种子
for i=1, 5 do
    data = data .. math.random(2) - 1
end
print(data)

如果您重新设置了种子或重新运行程序,请确保过去了超过 1 秒钟,因为 os.time() 返回表示秒的整数。

2021-12-28 14:49:40