The math.random()
function generates pseudo-random numbers. When called without arguments, it returns a pseudo-random float in the range ([0, 1)). When called with two integers (m) and (n), it returns a pseudo-random integer in the range ([m, n]). The call math.random(n)
for a positive (n) is equivalent to math.random(1, n)
, while math.random(0)
produces an integer with all bits (pseudo)random.
This function uses the xoshiro256** algorithm to produce pseudo-random 64-bit integers, which serve as the foundation for the other results (ranges and floats) generated by this function.
Syntax
math.random([m [, n]])
Parameters
- m (optional): The lower bound of the random integer range (inclusive).
- n (optional): The upper bound of the random integer range (inclusive). If only one argument is provided, it is treated as the upper bound.
Return Value
- When called without arguments: a pseudo-random float in the range ([0, 1)).
- When called with two integers (m) and (n): a pseudo-random integer in the range ([m, n]).
- When called with a single argument (n): a pseudo-random integer in the range ([1, n]).
- When called with (0): returns an integer with all bits pseudo-random.
Description
lua initializes its pseudo-random generator automatically, so each program run will generate different sequences of results unless a specific seed is provided using math.randomseed
.
Examples
Generating a random float
local randomFloat = math.random() -- Random float between 0 and 1
print(randomFloat)
Generating a random integer between two values
local randomInt = math.random(1, 10) -- Random integer between 1 and 10
print(randomInt)
Generating a random integer with one argument
local randomIntFromOneToN = math.random(5) -- Random integer between 1 and 5
print(randomIntFromOneToN)
Random Seed Initialization
To initialize the random generator with a specific seed, use math.randomseed
.
Example of using a seed
math.randomseed(os.time()) -- Initialize the random generator with the current time
local seededRandomInt = math.random(1, 100) -- Random integer between 1 and 100
print(seededRandomInt)
See also
math.randomseed()