【参考博文】Lua生成比较理想的随机数的方法
Lua生成随机数注意:
- 给随机数设置随机数种子:math.randomseed(xx)
- lua对随机数种子也是有一定要求的:不能太相近
- lua中的os.time()是基于秒的,不太满足lua对随机数种子的要求(如果设置随机数种子的频率太高的话)
解决方案:
把 os.time()返回的数值字串倒过来再取高位7位。 这样,即使 os.time()变化很小,随机数种子也会很大
math.randomseed(tonumber(tostring(os.time()):reverse():sub(1,7)))
例:
math.randomseed(tonumber(tostring(os.time()):reverse():sub(1,7))) –设置时间种子
for i=1, 15 do
print(math.random()) –产生0到1之间的随机数
print(math.random(1,100)) –产生1到100之间的随机数
end