math.random
Example
Generate a random number between 1 and 400 with both math.random and math.Rand.
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