简单来说,除去使用if-else实现外,自然就是使用table表来实现了,具体看代码:
function switch(a)
-- body
local switchNum = {
[1] = function() -- for case 1
print("Case 1.")
end,
[2] = function() -- for case 2
print ("Case 2.")
end,
[3] = function() -- for case 3
print ("Case 3.")
end
}
local switchStr = {
student = function() -- for case student
print ("Hi student, study hard remember.")
end,
teacher = function() -- for case teacher
print ("Hi teacher, thanks for your work hard.")
end,
coder = function() -- for case worker
print ("Go to Coding!!!.")
end
}
local switchTbl = {
table = function()
print("This's table.")
end
}
local switchBool = {
istrue = function()
print ("This's true.")
end,
isfalse = function()
print ("This's false.")
end,
}
-- 判断case的对象是否存在
local isExit = switchNum[a] or switchStr[a] or switchTbl[type(a)] or switchBool["is" .. tostring(a)]
if isExit then -- for case doyourself
local f = 0
if type(a) == "number" then
f = switchNum[a]
elseif type(a) == "string" then
f = switchStr[a]
elseif type(a) == "table" then
f = switchTbl[type(a)]
elseif type(a) == "boolean" then
f = switchBool["is" .. tostring(a)]
end
f()
else -- for case default
print "Case default."
end
end
switch(3)
switch(true)
switch("student")
switch({3})
print("=====================我是分界线==============================")
运行结果:
Case 3.
This's true.
Hi student, study hard remember.
This's table.
=====================我是分界线==============================