Better alternatives to this ContextActionService bind function?

So… Whenever I use ContextActionService, I make a function that handles the actions binded with it using if/elseif, but here’s the problem, if I make 4 or more actions, the function will definitely start to get messy.

It’s kind of a serious issue for me since I don’t know and can’t even think of another method other than if/elseif statements.

Here is an example of the function:

local function ActionHandler(ActionName, InputState, InputObject)
   if ActionName == "Holding" then
      Holding = InputState == Enum.UserInputState.Begin
   elseif ActionName == "Toggle" then
      ToggleBool = not ToggleBool
   elseif ActionName == "FireRemote" then
      ActionRemote:FireServer()
   end
end

Is there another option that I could use instead of potentially overusing if/elseif statements?

1 Like

Perhaps a table or a module would work? It isn’t really much cleaner but maybe it would help with organization.

local actions = {
    Holding = function(ActionName, InputState, InputObject)
        return InputState == Enum.UserInputState.Begin
    end;
    Toggle = function(ActionName, InputState, InputObject)
        ToggleBool = not ToggleBool
    end;
    FireRemote = function(ActionName, InputState, InputObject)
        ActionRemote:FireServer()
    end
}

local function ActionHandler(ActionName, ...)
    actions[ActionName](ActionName, ...)
end

As they said, a remote system or modules could work. You could alternatively bind actions via module names, and do say

local function ActionHandler(ActionName, InputState, InputObject)
   local moduleCode = require(game.Workspace.ModulePlace[ActionName])
   moduleCode.RunCode()
end

This modularizes code and makes it easy to find stuff.

1 Like

Oh! I didn’t know (or atleast, never thought) you could use modules that way. I’ll see what I can make using that method.

I really should start using modules more often…

1 Like