ITeye博客

switch

arust · 2009-05-11 11:16 · lang · 编程语言 · Markdown

一直对 Lua 没有 switch 语句耿耿于怀,每次检查代码时都不得不在令人眼花潦乱的 if then elseif 语句中检查配对关系,身心俱疲,视力受损。 :?

直到今天早晨突然想到可以用 repeat until 语句模拟,试验了一下,效果还不错,代码结构顿时清晰了许多。

而且,Lua 中的变量没有预定义的类型这一特性,使得这种写法比起 C 语言的 switch 语句更加灵活和强大。


table ={item="item"}

function func()
    print("hello world!")
end

function l_switch(str)
    repeat
        if str == true then
            print(str)
            break
        end
        if str == "abc" then
            print(str)
            break
        end
        if str == 123 then
            print(str)
            break
        end
        if str == func then
            func()
            break
        end
        if str == table then
            print(str.item)
            break
        end
        --default:
        print(str)
    until true
end

l_switch(true)
l_switch("abc")
l_switch(123)
l_switch(func)
l_switch(table)
l_switch(abc)

代码输出结果:

true abc 123 hello world! item nil

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。