Switch Statements In Lua

Switch

Use Switch Statements In Lua

Documentation | 💾 Download | 📃 Source



Sick of 20+ line if-statements? Use Switch instead to create better-looking switch statements in Lua easily!


Documentation

switch(condition: Condition, {[potentialResult: any] = code: any})

Example:

local switch = require(game.ReplicatedStorage.Switch)
local a = 100
local b = 70

switch(a > b, {
	[true] = function()
		print("worked!")
	end,
	[false] = function()
		print("hmm, didn't work!")
	end,
	["default"] = function()
		print("default")
	end,
})



Source Code


You can view the source code for Switch here. It's quite short!

I know I’ll get criticism for this being a module since its only 12 lines. You can just copy over the function if you’d like.




Thanks for reading & happy coding!
9 Likes

Non-nerdy and more simple version:

return function(condition,funcs)
	local FunctionToCall = funcs[condition]
	
	if FunctionToCall then
		FunctionToCall()
	end
end

This does not take into account default.

Never found a use case for default.

This is extremely false in the case of client-to-server input. For example, admin commands:

local someValue = getInputFromClient()

switch(someValue, {
    ['kick'] = function()
        -- kick
    end,
    ['ban'] = function()
        -- ban
    end,
    ['default'] = function()
        print("Not a valid command!")
    end
})
1 Like

default is basically if-statements’ else keyword.

You could make it take into account default though, it’s very similar to your code already except for ditching the unnecessary metatable and not having a condition for default which would be trivial to add. I’m not particularly sure why the metatable is there either since you don’t actually use any of the benefits of the metatable except for disguising a table as a function. Why…?

5 Likes

I’ve been learning C# as another language, and I was kind of annoyed that Lua didn’t have switches, as I found them to be very simple and useful. Pretty good module!

1 Like

This module is fine but it can be more simple. Also why your using a metatable?

return function(condition, functions)
	local func = functions[condition] or functions.default
	return type(func) == 'function' and func()
end
2 Likes

What is the justification for a metatable over a regular function? I don’t get it. Surely this could just be written as…

return function(item, cases)
    local value = cases[item] or cases.default
    if value ~= nil then
        return type(value) == "function" and value() or value 
    end
end

… right? I genuinely see no reason for the weird metatable, unless I am missing something.

You are correct, though the if value ~= nil thenend lines are unnecessary because keeping and removing them will have the same result.

The differences in time it takes to run, and memory usage is negligible, though my knowledge with Assembly makes me think otherwise, however the differences become negligible during benchmarking.

That being said, regardless of what benchmarking says, the metatable is unnecessary.

Still, though, best implementation of switch statements I’ve seen so far. Won’t personally use this but I am sure others will find use in it.

1 Like

I like my sanity checks damnit! But yes that is fair. The type check deals with that.

1 Like

There’s also this way, which is a bit unnecessary, but it’s interesting.

local function switch(condition)
	return function(results)
		local res = results[condition] or results['default']
		return (type(res) == 'function') and res() or res
	end
end

And then:

local animal = 'dog'

local result = switch(animal) {
	['cat'] = function()
		print('Meow')
		return 'This is a cat'
	end,

	['dog'] = function()
		print('Woof')
		return 'This is a dog'
	end,

	['default'] = 'Not a valid animal'
}

print(result)

Output:

Woof
This is a dog
1 Like