Switch

Switch is used to emulate a switch statement.

Switch(tbl)

In normal Lua syntax comparing a single value several times is repetitive and long.

Variable = 'Match1'
if Variable:lower() == 'match1' then
result = 'Example text.'
elseif Variable:lower() == 'match2' then
result = 'Other example text.'
else
result = 'No match found.'
end

Switch statements can make the code much shorter.

Variable = 'Match1'
Table = switch{
match1 = function(tbl) return tbl[2] end,
match2 = function(tbl) return tbl[2] end,
default = function(tbl) return 'No match found' end,
}
result = Table:case(Variable:lower(), 'Example text.')
-- Emulates a switch statement.
-- The functions in the switch table receive a table as a parameter.
-- The first index of the table is the match itself.
function switch(tbl) -- Used to emulate a switch statement
tbl.case = function(...)
local t = table.remove(arg,1)
local f = t[arg[1]] or t.default
if f then
if type(f) == 'function' then
f(arg)
else
print('Case: ' .. tostring(x) .. ' not a function')
end
end
end
return tbl
end