random()
In Lua, the math.random()
function is used to generate pseudo-random numbers. It can be used with or without an argument and in conjunction with the math.randomseed()
function to control the sequence of random numbers.
The ability to generate random numbers, especially when combined with seeds for reproducibility, has a wide range of applications in computer science, simulations, gaming, statistics, cryptography and more.
Note:
math.random()
does not truly generate random numbers since a seed algorithm is used for an initial value.
Syntax
The random()
method can be called with or a without a number using the following syntax:
math.random(x) -- Returns a random number between 1 and x.
math.random(x, y) -- Returns a random number between x and y.
- Parameters are optional for this method. If a number is not specified, a random number between
0
and1
will be generated.
Example 1
The following example shows the usage of math.random()
without a parameter:
print(math.random())
The output will be similar to the following:
0.78322180675329
Example 2
The following example shows the usage of math.random()
with parameters:
print(math.random(7))print(math.random(10, 15))
This will result in an output similar to the following:
512
Example 3
The following example shows the usage of math.random()
in conjunction with math.randomseed()
function:
math.randomseed(7)print(math.random())print(math.random())print(math.random())
This will result in the following output:
0.778981848967090.388080950064130.74830981146053
Note: Keep in mind that
math.randomseed()
will always generate a reproducible random sequence.
Looking to contribute?
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.