[size=medium]一直对 Lua 没有 switch 语句耿耿于怀,每次检查代码时都不得不在令人眼花潦乱的 if then elseif 语句中检查配对关系,身心俱疲,视力受损。 :?
直到今天早晨突然想到可以用 repeat until 语句模拟,试验了一下,效果还不错,代码结构顿时清晰了许多。
而且,Lua 中的变量没有预定义的类型这一特性,使得这种写法比起 C 语言的 switch 语句更加灵活和强大。
[/size]
[size=medium]
代码输出结果:
[/size]
[quote]true
abc
123
hello world!
item
nil
[/quote]
直到今天早晨突然想到可以用 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]