switch

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

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

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


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)

[size=medium]
代码输出结果:
[/size]
[quote]true
abc
123
hello world!
item
nil
[/quote]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值