Reputation: 83
In Lua 5.2.1, I tried to generate a random number with
num = math.random(9)
However, every time I run my program:
num = math.random(9)
print("The generated number is "..num..".")
I get the same number.
brendan@osiris:~$ lua number
The generated number is 8.
brendan@osiris:~$ lua number
The generated number is 8.
brendan@osiris:~$ lua number
The generated number is 8.
This is frustrating, because everytime I try to generate a new number and restart the program, I get the same sequence.
Is there a different way of generating a number?
Also, I've looked into
math.randomseed(os.time())
but I don't really get it. If this is indeed the solution could you explain how it works, what it does, and what number I'd get?
Thx,
Upvotes: 1
Views: 2303
Reputation: 131
First, you have to call 'math.randomseed()'
'Why?'
Because Lua generates pseudo random numbers.
--One of the best seeds for 'math.randomseed()' is the time.
So, you'll first write:
math.randomseed(os.time())
After this,
num = math.random(9)
print("The generated number is "..num..".")
However, there is a bug on Windows. Then if you just write 'num = math.random(9)' the generated number will be the same for 1 hour, i think.
'So how can I resolve this?'
It's easy, you need to do a for loop.
for n = 0, 5 do
num = math.random(9)
end
So, in Windows, the final code would be:
math.randomseed(os.time())
for n = 0, 5 do
num = math.random(9)
end
print("The generated number is "..num..".")
OBS: If 'for n = 0, 5 do' does not work perfectly, then replace 5 with 10.
Upvotes: 1
Reputation: 5723
In Lua this is the expected output. You are not guranteed to get different sequences across different sessions.
However, any subsequent calls to math.random
will generate a new number:
>> lua
> =math.random(9)
1
>> lua
> =math.random(9)
1
>> lua
> =math.random(9)
1
> =math.random(9)
6
> =math.random(9)
2
math.randomseed()
will change which sequence is replayed. If you set math.randomseed(3)
for example, you will always get the same sequence, just like above:
>> lua
> math.randomseed(3)
> =math.random(9)
1
> =math.random(9)
2
> =math.random(9)
3
>> lua
> math.randomseed(3)
> =math.random(9)
1
> =math.random(9)
2
> =math.random(9)
3
If you however set math.randomseed()
to a unique value each run, for example os.time(), you will ofcourse get an unique sequence each time.
Upvotes: 2
Reputation: 72362
This is not particular to Lua. Pseudorandom generators usually work like that: they need a seed to start and the sequence they generate is not really random, but actually deterministic given a seed. This is a good thing for debugging but for production you need to alter the seed in a "random" way. An easy and typical way of doing that is to use the time to set the seed once at the start of the program.
Upvotes: 5