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: Random in Range

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

print( 'Random Integer [ 1 , 400 ) :' , math.random( 1 , 400 ) )
Output:
Random Integer [ 1 , 400 ) : 317


Example: Random Table Key

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
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy