Lua - 实现switch case

简单来说,除去使用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.
=====================我是分界线==============================

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值