C语言的Switch,不加break,可以实现选择一个函数的开始执行位置,而且他们的结束位置是相同的,那么lua语言中怎么实现呢?
请看这里的各种模拟:http://lua-users.org/wiki/SwitchStatement
问题已解决,lua支持goto语句,goto语句可以实现上述功能,当然通过递归调用也是可以的
lua没有switch语句,加一个很方便,连头带尾9句话(话说,lua真优美啊。。。。):
function switch(SwitchVal) --模拟C中的switch
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,"1","2","one","two"}
for _, i in ipairs(t) do
switch(i){ --是不是很像C?
[1] = function()
print(1)
end,
["1"] = 1, --多个标签对应一个分支的写法
["one"] = 1,
default = function() --支持default
print("default")
end,
}
end