Lua math.random() always gives the same number?

Viewed 472

I wanted a string to contain 0 or 1 for some project. So i tried this

local data = ""
for i=1, 5 do
    data = data .. math.random(2) - 1
end
print(data)

This program always gives 10111 as the result. So after searching i got this similar question. Link So I changed my program to like this as mentioned in that program

local data = ""
for i=1, 5 do
    math.randomseed(os.time())
    data = data .. math.random(2) - 1
end
print(data)

And also this

local data = ""
for i=1, 5 do
    math.randomseed(os.time())
    math.random(2)
    math.random(2)
    math.random(2)
    data = data .. math.random(2) - 1
end
print(data)

So when i tried this one also it always gives 11111 or 00000 as the output. Why?? And how to correct it so that I can get random 0 or 1 in my string??

1 Answers

Add the seed before the loop:

local data = ""
math.randomseed(os.time())
for i=1, 5 do
    data = data .. math.random(2) - 1
end
print(data)

if you reseed or rerun your program, make sure that more than 1 second has passed, as os.time() returns the time in seconds, represented by an integer.

Related