How would I choose a random function inside a module script

I have made a list of events inside a module script but I’m struggling to choose between them and all my attempts will result in a Nil value being called instead.

This is how I store the functions inside the module script:

local Events = {}

function Events.Event1()-- this is an example name
  -- my code here
end

return Events

Am I doing something wrong?

The only idea I have in my mind is that you create a function that calls a random function created inside that module script. The functions would be stored in a number-based index array.

Would you demonstrate how could I do the number-based index array? thank you

Maybe something like this:

local Events = {}
local EventsNames = {"Event1", "Event2"}

function Events.RandomEvent()
    local chosen = EventsNames[math.Random(1, #EventsNames)]
    Events[Chosen]()
end

function Events.Event1()-- this is an example name
  -- your code here
end

return Events

Completely untested and probably won’t work. but it still could work so IDK

Is it possible to do this outside the module script?

Probably. Just move the RandomEvent code and the EventNames code to another one

1 Like

You can use Syntatic Sugar

function Events.RandomEvent()
    local r = math.random(1, #Events)
    Events[r]()
end

Events.Event1 = function()

end