Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

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

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

3 answers

Log in to vote
0
Answered by 3 years ago

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 30 — 3y
Ad
Log in to vote
0
Answered by 3 years ago
Edited 3 years 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 32 — 3y
0
There was a "invalid argument #2 to 'random' (interval is empty)" error that occurred as well. OscarTheRobloxPlayer 32 — 3y
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 597 — 3y
Log in to vote
0
Answered by
c_odez 20
3 years ago

You can use the NextInteger function of Random.

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

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

Answer this question