您的位置:首页 > 编程语言 > Lua

Lua实现switch case

2019-06-12 18:13 3335 查看

简单来说,除去使用if-else实现外,自然就是使用table表来实现了,具体看代码:

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()    -- for case student
        print ("This's true.")
    end,
    isfalse = function()    -- for case teacher
        print ("This's false.")
    end,
}

local a = "coder"
local a = 3
local a = true
local a = {}
-- 判断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

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: