简体   繁体   English

如何在每次运行lua脚本时生成随机值

[英]how to generate random value in each time I run the lua script

I have written a lua script named "lua_rand_gen" which contains following code: 我编写了一个名为“ lua_rand_gen”的lua脚本,其中包含以下代码:

function random_number_func()
    math.randomseed(os.time())
    return (math.random(100000000,999999999))
end

print (random_number_func())


when I run the lua_rand_gen script in the terminal in loop , the above function is not generating randome values as shown : 当我在终端循环中运行lua_rand_gen脚本时,上述函数未生成如下所示的randome值:

for ((i=0;i<=5;i++)); do lua lua_rand_gen; done

717952767
717952767
717952767
717952767
717952767
717952767


I know this is because os.time() doesn't change till one second. 我知道这是因为os.time()直到一秒钟才改变。 So, how can I get Random number in lua if the time difference between running the lua script is less than 1 sec. 因此,如果运行lua脚本之间的时间差小于1秒,如何在lua中获得随机数。

Move math.randomseed(os.time()) outside the function. math.randomseed(os.time())移动到函数外部。

It seems to be a common misconception that you need to call math.randomseed before each time you call math.random . 这似乎是一种常见的误解,即您每次调用math.randomseed之前都要先调用math.random This is wrong and will defeat the randomness of math.random , especially if you use os.time() as seed, since the seeds will be the same for a whole second. 这是错误的,并且会os.time() math.random的随机性,尤其是如果您使用os.time()作为种子,因为种子在一秒钟的时间内都是相同的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM