Garry's Mod Wiki

math.random

number math.random( number m = nil, number n = nil )

Description

When called without arguments, returns a uniform pseudo-random real number in the range 0 to 1 which includes 0 but excludes 1.

When called with an integer number m, returns a uniform pseudo-random integer in the range 1 to m inclusive.

When called with two integer numbers m and n, returns a uniform pseudo-random integer in the range m to n inclusive.

See also math.Rand

Arguments

1 number m = nil
If m is the only parameter: upper limit.

If n is also provided: lower limit.

If provided, this must be an integer.

2 number n = nil
Upper limit.

If provided, this must be an integer.

Returns

1 number
Random value

Example

Generate a random number between 1 and 400 with both math.random and math.Rand.

print(math.random(1,400)) print(math.Rand(1,400))
Output: 317 1.0162317198768

Example

Select a random key from a table, where the keys have a different probability of being selected.

function GetWeightedRandomKey(tab) local sum = 0 for _, chance in pairs(tab) do sum = sum + chance end local select = math.random() * sum for key, chance in pairs(tab) do select = select - chance if select < 0 then return key end end end -- Example usage: local fruit = { Grape = 4.5, Orange = 20, Banana = 3.14 } for i = 1, 5 do print(GetWeightedRandomKey(fruit)) end
Output: Banana Grape Banana Orange Orange

Page Links


Special Pages


Wikis

?

Render Time: 32ms

Session 0
DB GetPage 3
Generate Html 6
SaveChanges 10
Render Body 0
Render Sidebar 11