math.random

Shared

Generates a pseudo-random number


Syntax

-- Random float in [0, 1)
local result = math.random()

-- Random integer in [1, max]
local result = math.random(
    max
)

-- Random integer in [min, max]
local result = math.random(
    min,
    max
)

Parameters

TypeNameDescription
intmaxUpper bound when called with one argument
intminLower bound when called with two arguments
intmaxUpper bound when called with two arguments

Returns

TypeNameDescription
numberresultGenerated pseudo-random number:
float in [0, 1) — when called with no arguments
int in [1, max] — when called with one argument
int in [min, max] — when called with two arguments

Examples

Generate a random float between 0 and 1
local result = math.random()

engine.print("info", result) -- 0.12345 (varies)
Generate a random integer between 1 and 10
local result = math.random(10)

engine.print("info", result) -- 7 (varies)
Generate a random integer in a custom range
local result = math.random(5, 15)

engine.print("info", result) -- 11 (varies)
Simulate a coin flip
local flip = math.random(0, 1)

if flip == 0 then
    engine.print("info", "Heads")
else
    engine.print("info", "Tails")
end
Pick a random element from a table
local items = {"sword", "shield", "potion", "arrow"}
local picked = items[math.random(#items)]

engine.print("info", picked) -- 'potion' (varies)
Generate a random float in a custom range
local range_min, range_max = 1.5, 4.5
local result = range_min + math.random() * (range_max - range_min)

engine.print("info", result) -- 2.87 (varies)
Roll a six-sided die
local roll = math.random(1, 6)

engine.print("info", "Rolled:", roll)
Shuffle a table using random swaps
local t = {1, 2, 3, 4, 5}

for i = #t, 2, -1 do
    local j = math.random(i)
    t[i], t[j] = t[j], t[i]
end

for _, v in ipairs(t) do
    engine.print("info", v)
end

On this page