I have only seen modules which is kind of inconvenient since I’d rather be able to directly get it and as lightweight as possible, also for you developers complaining about why we should have switch cases. This post speaks to the audience as if they are a Lua beginner that has used another language.
How to make do similar operation as a switch case? Switch cases are often useful as in other programming languages, they’re fast and readable. For Lua(and U), they’re just more readable than if … elseif … but they’re often pretty slow.
This is the whole code… you can modify it yourself.
local function switch(invar)
if not invar then return end
return function(cases)
for k, v in pairs(cases) do
if invar == k then
v()
return
end
end
if cases["default"] then cases["default"]() end
end
end
How to use it?
local mivar = "bar"
switch(mivar){
["foo"] = print("foo"),
["bar"] = print("bar"),
["baz"] = print("baz").
["default"] = print("NOTHING!!!!111")
}
-- OUTPUT: bar
How does one provided above works?
We create the function with the variable and return them to callback. The function loops through the table and if nothing matches then it launches default
which means default
is taken in this case. The function uses one of Lua’s flaw to pass the table in. That is… being able to put arguments without enclosing it in parenthesis which is a bad practice. If we’re really looking into on how it’s representing…
switch()({})
-- They're both the same
switch(){}
Why you shouldn’t use in many cases?
It shouldn’t be used often in big projects as it is really unoptimized and not really up to the standard convention according to most of Lua programmers. If you are a programmer of another language who misses the touch of switch cases, this is fine… for personal projects.
One of the purposes of this post though is to show you how cool Lua’s flaws can be when it comes to using it in an unintended way.