短处是分支只对单个标签有效

葡京网站spj3355,Lua未有switch语句,大家就给它加一个:

一、简单的switch:

function switch(SwitchVal)
    return function(SwitchTable)
        local ReFunc = SwitchTable[SwitchVal]
        if type(ReFunc) ~= "function" then
            ReFunc = SwitchTable[ReFunc] or SwitchTable.default
        end
        return ReFunc and ReFunc()
    end
end

亮点是落到实处简单,劣势是分段只对单个标签有效,假使多个分层对应若干个标签,写起来就比较费心,请看例子:

t = {1,2,3,"1","2","3","one","two","three","default"}
one = "one"
for _, i in ipairs(t) do
    switch(i){
        [1] = function()
            print(1)
        end,
        ["2"] = function()
            print('"2"')
        end,
        ["1"] = 1,    --多个标签对应一个分支的写法
        ["two"] = "2",
        default = function()
            print("default")
        end,
    }
end

二、复杂点的switch:

function switch(SwitchVal)
    return function(SwitchTable)
        local ReFunc = SwitchTable.default
        for _, v in ipairs(SwitchTable) do
            if type(v) == "table" then
                for _, vv in ipairs(v) do
                    if vv == SwitchVal then
                        ReFunc = v[#v]
                        break
                    end
                end
            end
        end
        return ReFunc and ReFunc()
    end
end

本条改良了地方拾叁分的后天不良,标签仍然是能够使用“default”,和switch的default不矛盾。请看例子:

t = {1,2,3,"1","2","3","one","two","three","default"}
one = "one"
for _, i in ipairs(t) do
    switch(i){
        {1,"1",one,     function()
            print(1)
        end},
        {2,"2","two",   function()
            print(2)
        end},
        {"default",     function()
            print("default")
        end},
        default = function()
            print(0)
        end,
    }
end