我在Lua中使用math.random()函数遇到了问题。 我尝试运行的代码是:
for x = 1,5 do
math.randomseed(os.time())
math.random(); math.random(); math.random()
value = math.random(0,9)
print(value)
end
被打印出来的随机数总是相同的。
有什么可能的解决方案吗?我想要5个独立的随机数。
在循环之外只随机一次(初始化),然后多次使用:
math.randomseed(os.time()) -- random initialize
math.random(); math.random(); math.random() -- warming up
for x = 1,5 do
-- random generating
value = math.random(0,9)
print(value)
end
math.randomseed(os.time())
放在循环体外。 - Dmitry Bychenko