math.random

From Garry's Mod
Jump to: navigation, search
 math.random( )

Contents

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.

Arguments

number m

If m is the only parameter: upper limit.
If n is also provided: lower limit.

If provided, this must be an integer.

Arguments

number n

Upper limit.

If provided, this must be an integer.

Returns

number

Random value

Examples

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

Examples

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
Personal tools
Navigation