I am trying to use lua to produce a random number, but it simply spits out the lowest value. For instance, if I run:
x = math.random(17,41)
print(x)
It returns:
17
What is wrong?
That is not necessarily true. All random numbers are not entirely random. As an example, you can take a look at this working code; which is the same as you posted in question: http://eval.in/17806
The output as you can see is 38.
To quote from Doub's reply:
You can use
math.randomseed
to start the pseudo-random sequence elsewhere. You can useos.time
to initialize that with a different value every time you run the program (assuming you allow at lease one second to elapse between runs).
Here is an example for the same program with randomseed
in action: http://eval.in/17808
math.randomseed( os.time() )
x = math.random(17,41)
print(x)
Lua uses the C runtime library pseudo-random number generator. Its properties depend on your platform. For example on (some versions of) Windows, the generator is always initialized at the same point of the pseudo-random sequence, so you always get the same sequence of values when running your program (see http://msdn.microsoft.com/en-US/library/f0d4wb4t.aspx).
You can use math.randomseed to start the pseudo-random sequence elsewhere. You can use os.time to initialize that with a different value every time you run the program (assuming you allow at lease one second to elapse between runs).
Note also that on some Windows C runtime libraries, the first pseudo-random value you get after calling srand (or math.randomseed in Lua) is very dependent on the value you pass. So I would recommend calling math.random once and ignoring its result after calling math.randomseed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With