Randomization question

quick question about how randomseed can be used. i want to be able to generate a random number between 1 and 4, and use system time for fairly accurate randomization.
how exactly does it work? the system i tried to use has it as 4 as the upper bound, and then +1 to make sure the output isn’t 0.

math.randomseed(4 * os.time() + 1)

math.randomseed() is not used to generate random numbers. Rather, it is used to… Well, seed the random numbers. If you provide the same seed, the output sequence of math.random() will always be the same.

Using time is a good idea to get a random seed. Here’s how I do it:

    math.randomseed (100000000000000 * (socket.gettime() % 1))
    for i=1,20 do
        math.random()
    end

The for loop is to clear the first few ‘bad’ rolls, and is not strictly necessary.

Once you’ve set your seed, what you want to do to get a random number between 1 and 4 is simple:

math.random(1,4)
1 Like

cool thanks

This should no longer be needed. The issue was fixed a while back: https://github.com/defold/defold/pull/6235

1 Like