1

I have written a lua script named "lua_rand_gen" which contains following code:

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 :

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. So, how can I get Random number in lua if the time difference between running the lua script is less than 1 sec.

Abhishek
  • 139
  • 2
  • 13

1 Answers1

0

Move math.randomseed(os.time()) outside the function.

It seems to be a common misconception that you need to call math.randomseed before each time you call 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.

lhf
  • 70,581
  • 9
  • 108
  • 149
  • IMO, function name `randomseed(seed)` is not informative for beginners. Probably, `startrandomsequence(sequenceid)` would be more clear? – Egor Skriptunoff Mar 03 '16 at 13:03
  • "lua_rand_gen" is a script file each time i run the script it executes the function writen the lua_rand_gen file (which is mentioned above) and exits , and I am not getting random numbers if I the run the script within the time interval of 1 secound – Abhishek Mar 07 '16 at 08:56