About math.random()

Last updated 14 days ago

When you call math.random() without setting a seed you will get the same values each time every time you run your game. This is due to the way "random" values are generated. Generally you would set the seed to os.time() to make the "random" generation based on the current timestamp of the user, which functionally makes your random generation look to actually be random each time your game is ran, but would still generate the same random numbers each time if you used the same timestamp.

There is another issue however - the first few values generated by math.random() are usually the same no matter what. This is due to the way the builtin Lua RNG method generates numbers. To compensate this, you should always dispose of the initial values generated.

math.randomseed(os.time()) -- sets seed to the current time
math.random();math.random();math.random(); -- discards first few RNG numbers
print(math.random(), math.random(), math.random()) -- some random numbers between 0 and 1
print(math.random(0,1), math.random(0,1), math.random(0,1)) -- either 0 or 1 randomly