Trying to Make a Random Function Happen

Hi, I am a new scripter and am trying to make a function run at random but whenever I would play test, it would run the first thing in the table.

So how can I make it run a random function?

2 Likes

The functions are independent variables, you have to add them to a table so that the script can run them

local myFunctions = {}

myFunctions.Swag = function()
   -- do stuff
end

Alternatively, you could use getfenv to the script’s environment, but I don’t recommend that

And for the script to get a random function, it would have to create a dummy table (an array) to insert the function’s indexes because you wouldn’t be able to use math.random on a dictionary table

local myFunctions = {} -- the table
local dummyTable = {} -- table to hold the index's do the script can use them later

-- the functions in the table
myFunctions.Swag = function()
   print("swag ran")
end

myFunctions.no = function()
   print("no ran")
end

for index, func in pairs(myFunctions) do -- loops through the functions table
   table.insert(dummyTable, index) -- adds the index to the dummy table
   -- the index would be something like:
   -- myFunctions.no = function() | "no" would be the index
end

myFunctions[dummyTable[math.random(1, #dummyTable)]]() -- this will get a random index from the dummy table, and find it in the main table, and then run it

Developer Hub Articles:

https://education.roblox.com/en-us/resources/pairs-and-ipairs-intro

2 Likes