table.Random

From Garry's Mod
Jump to: navigation, search
 table.Random( )

Contents

Description

Returns a random value from the supplied table.

NOTE This function iterates over the given table twice, therefore with sequential tables you should instead use following:
mytable[ math.random( #mytable ) ]

Arguments

table haystack

The table to choose from.

Returns

any

A random value from the table.

Returns

any

The key associated with the random value.

Examples

Example

A simple example of this function using two tables.

color = { "green", "red", "blue", "yellow" }
object = { "car", "house", "bike" }

print( "I have a " .. table.Random( color ) .. " " .. table.Random( object ) .. "." )

Output:

I have a green house.

Examples

Example

Example of using the alternative with sequential tables for performance reasons.

websites = {"facepunch.com", "google.com", "steampowered.com"}
print("I think the best website ever is " .. websites[math.random(1, #websites)] .. ".")

Output:

I think the best website ever is google.com.
Personal tools
Navigation