Generating uniform random numbers in Lua

You need to run math.randomseed() once before using math.random(), like this:

math.randomseed(os.time())

From your comment that you saw the first number is still the same. This is caused by the implementation of random generator in some platforms.

The solution is to pop some random numbers before using them for real:

math.randomseed(os.time())
math.random(); math.random(); math.random()

Note that the standard C library random() is usually not so uniformly random, a better solution is to use a better random generator if your platform provides one.

Reference: Lua Math Library

Leave a Comment