math.random
What you're looking for is the math.random
function in the math
library. This function has a very simple mechanic to it; you input a number, and it outputs a random number given the range. We can utilize this randomly generated number in many ways, and in this case, solve the problem of receiving a random value from your array.
Arguments
In case this wasn't clear from the introduction above, math.random
only deals with numbers. Meaning the argument we must input, has to be a number. The amount of arguments you give this function will effect the outcome in different ways. Here are some examples:
1: Using a single argument
By returning a single number to this function, it will generate a random number between 1, and whatever number you gave it. Like this:
2: Using 2 arguments
Or, we could create our own range of numbers by providing the function with a second argument. This new range will return a random number between the first argument, and the second. Like this:
1 | print (math.random( 10 , 20 )) |
3: Using no arguments
It's important to note that math.random only returns whole numbers. Even if you provide a number with a decimal. The only way you can get a random decimal number, is by calling math.random()
with no arguments. Which will return a random decimal between 0 and 1. Here's an example:
If you wanted a decimal number larger than 1, you could simply multiply the result:
1 | print (math.random()* 100 ) |
Getting a random value
Now for the actual part of your question, getting the random value. Well, this should be pretty simple at this point if you know how to index an array-styled table. We can simply use brackets with the given random number on the table to return the random value, like this:
1 | local Table = { "Player1" , "Player2" , "Player3" } |
2 | local Rand = math.random(#Table) |
Or to make things quicker, we could do this:
1 | local Table = { "Player1" , "Player2" , "Player3" } |
3 | print (Table [ math.random(#Table) ] ) |
Non-array styled tables?
If you've noticed from above, we can easily return the amount of content in an array by using the #
symbol before it. However, this will not work for dictionary-styled
tables. A dictionary styled table is an array, with defined keys
. Here's an example:
02 | local Dictionary = { x = 1 , y = 2 , z = 3 } |
14 | local Array = { 'x' , 'y' , 'z' } |
Problem
However, this will not work for dictionary styled tables. Since we've overwritten all the numeric keys (in the case of a dictionary table), our ability to sense how much data is in the table is gone. We would have to find a way to convert our dictionary table to an array, and then index it with a random number. Here's an example:
01 | local Dictionary = { x = 1 ,y = 2 ,z = 3 } |
04 | local function ConvertDictionaryToArray(d) |
12 | local ArrayVersion = ConvertDictionaryToArray(Dictionary) |
15 | print (ArrayVersion [ math.random(#ArrayVersion) ] ) |
Hope this helped.