Lua Random Numbers
Lua random numbers are values picked by the math library from a range you choose. A seed makes the picks follow a repeatable sequence.
Seed first, then pick
Setting seed 1234 fixes the sequence before any pick is made. The first pick from a range of 100 is then always 67.
math.randomseed(1234)
print(math.random(100))Three picks in sequence
Each math.random call moves to the next value in the seeded sequence. With seed 1234 the first three picks are fixed.
math.randomseed(1234)
print(math.random(100), math.random(100), math.random(100))Seeding again restarts the sequence
Calling math.randomseed with the same seed starts the sequence over. The next pick is the first value again.
math.randomseed(1234)
print(math.random(100))
math.randomseed(1234)
print(math.random(100))Example
math.randomseed(1234)
local first = math.random(100)
local second = math.random(100)
local third = math.random(100)
print(string.format("First: %d", first))
print(string.format("Second: %d", second))
print(string.format("Third: %d", third))Key points
- math.random: a tool that picks a whole number from 1 up to the limit you give it.
- math.randomseed: a tool that sets the starting point for the random sequence.
- Seed: a number given to math.randomseed that fixes which sequence follows.
- Repeatable sequence: the same seed always starts the same series of random picks.
In this example, the seed 1234 is set once before any draws are made. The three math.random calls then take the first three values of that fixed sequence in order. string.format labels each draw on its own line.
Note
a program that never sets a seed can give different picks each time it runs.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does math.randomseed do in a program?