lua需要生成随機數的需求也是很常見的,為了生成看起來更随機的數字,我們需要注意以下幾點
- 我們也需要給随機數設定随機數種子:math.randomseed(xx)
- lua對随機數種子也是有一定要求的:不能太相近
- lua中的os.time()是基于秒的,不太滿足lua對随機數種子的要求(如果設定随機數種子的頻率太高的話)
那怎麼做?
把 os.time()傳回的數值字串倒過來再取高位7位。 這樣,即使 os.time()變化很小,随機數種子也會很大
math.randomseed(tostring(os.time()):reverse():sub(1, 7))
例:
math.randomseed(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
轉自:https://www.cnblogs.com/gggzly/p/5947892.html