Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

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

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

3 answers

✓ Accepted answer

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)]

1 comment

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.

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. ;)

3 comments

0

I thought of that but I did not want to use a variable as a result.

0

There was a "invalid argument #2 to 'random' (interval is empty)" error that occurred as well.

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.

You can use the NextInteger function of Random.

local teams = {red(), green(), blue(), yellow()}

print("Team " .. teams[Random.new():NextInteger(1, #teams)] .. " chosen!")

This discussion is preserved as it was. New answers, comments, and votes are closed.