Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua random number generation

I am having trouble with the math.random() function in Lua. The code I'm trying to run is:

 for x = 1,5 do
    math.randomseed(os.time())
    math.random(); math.random(); math.random()
    value = math.random(0,9)
    print(value)
end

The random number that is being printed is always the same.

What can be the possible solution to this? I want 5 unique random numbers.

like image 511
Shiladitya Bose Avatar asked May 05 '26 06:05

Shiladitya Bose


1 Answers

Initialize random once (outside the loop), use many:

math.randomseed(os.time()) -- random initialize
math.random(); math.random(); math.random() -- warming up

for x = 1,5 do
    -- random generating 
    value = math.random(0,9)
    print(value)
end
like image 61
Dmitry Bychenko Avatar answered May 06 '26 19:05

Dmitry Bychenko