Lua 5.1.4中的math.random实际上不是真正的随机。

我的问题是当我写math.random(10)时,它实际上不是随机的,它总是给出输出:

1 6 2 9

如果我例如使用了:

local colors = {"ORANG","BLUE","RED","YELLOW","BLACK"}
print(colors[math.random(#colors)])
print(colors[math.random(#colors)])
print(colors[math.random(#colors)])
print(colors[math.random(#colors)])
print(colors[math.random(#colors)])
print(colors[math.random(#colors)])
print(colors[math.random(#colors)])
print(colors[math.random(#colors)])
os.execute 'pause'

输出总是:

ORANGE
RED
ORANGE
BLACK
RED
RED
BLUE BLACK

这总是输出,怎么可能是随机的????

点赞
用户4433386
用户4433386

你误解了 random 函数的作用:

它是一个伪随机数生成器,这意味着,给定特定的种子,它总是会给出完全相同的数字序列。

通常情况下,你从外部来源使用种子,例如使用当前时间作为种子(注意:这在加密方面是危险的!)。

请阅读有关伪随机数和如何使用 Lua 的随机库的资料。

2015-06-04 10:57:06
用户3601294
用户3601294

我找到了答案,你需要如下操作:

math.randomseed(os.time())
math.random(); math.random(); math.random()

然后才能使用 math.random() 函数。

2015-06-04 11:08:58