You need to seed the random number generator.
Lua's math.random()
function corresponds to C's rand()
function.
In C, the rand()
function returns the next value in a sequence determined by the initial seed. The default initial seed value is 1
, which means that the program will use the same sequence each time it's run (which can be useful if you need reproducible results).
To get more nearly random results, you need to initialize the seed, for example, using the current time.
In C, this can be done like this:
srand(time(NULL));
int r = rand();
The corresponding Lua code is:
math.randomseed(os.time())
print(math.random())
Note that os.time()
typically returns the current time as a whole number of seconds, so you'll get the same seed if you run your program twice within the same second. Also, C's rand()
function and therefore Lua's math.rand()
function, is generally not a high-quality pseudo-random number generator; do not use either for applications, like cryptography, requiring unpredictable values. (There are better PRNGs, but they're beyond the scope of this question.)