Is there a way to randomly choose and run a function in a ModuleScript?

I’m currently making a tile game, and I want random things to happen to the tiles. I have a central script in ServerScriptService which controls the events in my game. There’s a module script inside of it called ‘Functions’ which houses all the random events I want to run.

Screen Shot 2021-04-13 at 7.50.30 PM

My question is, is there a way to randomly select and run functions that are in that module script?

GameManager:

local functions = require(script.Functions)

while true do
    -- I want to randomly select a function from the module script and play it here
end

Functions:

local functions = {}

function functions.SetBrickOnFire()
    print('Set brick on fire')
end

function functions.ChangeBrickColor()
    print('Changed brick color')
end

return functions

I want the script to choose between all the functions and select one, then run it. Is this possible?

If more clarification is needed, please let me know. All input is appreciated, thanks!

1 Like
local randomFunc = functions[math.random(1, #functions)]
-- modulescript's return a table (pretty sure i'm on mobile)

make a table of all the functions

local MethodNames = {}

for MethodName, Method in pairs(Module) do
    if type(Method) == "function" then --make sure that this value is a function
         table.insert(MethodNames, MethodName)
    end
end

then pick a random one

local RandomMethodName = MethodNames[math.random(1, #MethodNames)]

get the funtion

local Method = Module[MethodName]

and use this to call it

Method()
8 Likes