Simple switch statement module

That is actually literally how my module works, but more cleaner.
I used to do this when I started learning about mapping values to tables:

local UserInputService = game:GetService("UserInputService")

local KEYCODE = Enum.KeyCode
local maps = {
    [KEYCODE.W] = function()
        -- ...
    end;
    ...
}

UserInputService.InputBegan(function(input: InputObject, gpe: boolean)
    local keycode = input.KeyCode
    if (maps[keycode]) then maps[keycode]() end
end)

But this is just a cleaner way of doing it:

local UserInputService = game:GetService("UserInputService")

local switch = require(...)

local KEYCODE = Enum.KeyCode


UserInputService.InputBegan(function(input: InputObject, gpe: boolean)
    local keycode = input.KeyCode
    
    switch(keycode)
    :Case(KEYCODE.W, function()
         -- ...
    end)()
    ...
end)

As I’ve stated before, this is just personal preference and there isn’t much to discuss.

I like switch statements, but unless they’re implemented directly into luau by Roblox, they won’t be nearly efficient or as easy to use as elseif chains.

Good idea, but it’s not something I would use as I value efficiency for something as primitive as a switch statement.

1 Like

Cool module. Switch statements in luau is something I would only consider when experimenting but definitely not in game production code. Not only does it take longer to implement switch statements rather than if statements, the module as a whole seems like an unnecessary abstraction.

This point isn’t really significant. When benchmarking multiple elseif chains, the speed it took for the luau VM to execute the following code per iteration averaged around 0.00000001. In an actual game, these “speed drops” are not close to being noticeable by the human eye.

local A = 10

for i = 1, 10 do
	local StartTime = os.clock()
	if A == 1 then

	elseif A == 2 then

	elseif A == 3 then

	elseif A == 10 then

	end
	print(os.clock() - StartTime)	
end

Worrying about micro-optimizing is pointless and wastes your time being productive. There is a reason micro-optimizations are considered to be “the root of evil”.

Even from a micro-optimization perspective, your method seems more inefficient since everytime that listener is called, you are allocating a function to memory per case. It is important to keep code simple and optimized to a certain / noticeable extent.

I am fully aware it’s less performant. This module isn’t meant to be an optimization for elseif statements, but rather a way to imitate switch statements.