Still have questions? Join our Discord server and get real time help.
0

# Is there a way to call an index from an array randomly and without a variable as the result?

Edited 7 days ago
local teams = {red(), green(), blue(), yellow()}
-- This line should pick one random index from the array.


0

Is your question that you want to call the function 'red' when the random index is 1?

If so, then the answer would be:

-- If you don't need to return anything from the call, then just remove the returns
local teams = {
function()
return red()
end,
function()
return green()
end,
function()
return blue()
end,
function()
return yellow()
end
}

-- OR

local teams = {}
teams[1] = red
teams[2] = green
teams[3] = blue
teams[4] = yellow

-- AND THEN

teams[math.random(1, #teams)]() -- This will call the function stored in the table


If not, then you should rephrase to "access an index" instead of "call an index" and your answer would just be:

teams[math.random(1, #teams)]

0
The way you have the teams table set up now, it would call every function and store the results in the table instead of storing the function in the table. HxterNinja 15 — 6d
0
Edited 7 days ago

When calling an index from an array you use "[number]". Knowing this, you can use "math.random(minimumNumber, maximumNumber)" to generate a pseudo-random number. In order to obtain the amount of objects in an array, you use the "#" symbol followed by the name of the array.

teams = {red(), green(), blue(), yellow()}
randomTeam = teams[math.random(1, #teams)];


This will work, though, if you call upon it when there are 0 objects in the array, you will get "nil" instead.

If you have any questions or issues, contact me. ;)

0
I thought of that but I did not want to use a variable as a result. OscarTheRobloxPlayer 14 — 7d
0
There was a "invalid argument #2 to 'random' (interval is empty)" error that occurred as well. OscarTheRobloxPlayer 14 — 7d
0
You will receive a variable from the list regardless that you store it or not. If you want a number rather than the variable from the teams list (red(), green(), blue(), etc.) just use "math.random(1, #teams)" in order to receive a random number from the amount of objects in the array -- still assuming that you always have at least one object in the array. lazycoolboy500 537 — 5d
local teams = {red(), green(), blue(), yellow()}