`
arust
  • 浏览: 93868 次
  • 性别: Icon_minigender_1
  • 来自: 海底
社区版块
存档分类
最新评论

switch

    博客分类:
  • lang
阅读更多
一直对 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

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics