Posted 24 February 2016 - 07:43 AM
A friend of mine who I have been trying to get to switch over to Lua was busy complaining that there isn't a switch statement in the language. After trying and failing to convince him to just use if .. elseif. I resorted instead to just writing a switch statement for him. He didn't like this either though since it didn't handle regular expressions/patterns. Since I had to admit that would give it an advantage over normal if statements I ended up writing it. Here is the code snippet for anyone interested along with usage examples
local function switch(vInput) --#our function magic at work
return function(tCases)
local sent = vInput
if type(vInput) == "string" then
for k,v in next, tCases do
if type(k)=="string" then
local s, e = vInput:find(k)
if s==1 and e==#vInput then
vInput = k
break
end
end
end
end
if tCases[vInput] then
tCases[vInput](sent)
elseif tCases["_"..type(vInput)] then
tCases["_"..type(vInput)](sent)
elseif tCases._default then
tCases._default(sent)
end
end
end
--[[#
#thats the end of the snippet
#
#everything below is just example
#]]
function foo(bar) --#function to demonstate switches
switch(bar) --#compare all cases to whatever was passed as bar
{
["%d+"] = function(x) print(x..", is all digits") end; --#run if given string with all digits
["%a+"] = function(x) print(x..", is all letters") end; --#run if given string with all letters
[5] = function(x) print(tostring(x)..", is numeral five") end; --#run if given five
_number = function(x) print(tostring(x)..", is a number but i know it isnt five") end; --#for any number not five
_table = function(x) print(tostring(x)..", well thats a table") end; --#run if given a table
_default = function(x) print(tostring(x)..", ...well we don't have a handle for this") end; --#run this if none of the rest were true
}
end
--#each of these will run through each case in order
foo("foobar")
foo("12345")
foo(5)
foo(95)
foo({"a table"})
foo("password1 is a very bad password")
Edited on 24 February 2016 - 06:46 AM