继上一篇介绍了 Lua 中 Continue 的玩法,温总回复说可以用下 goto
。那么这篇就来说说 goto
的用法。
Lua 在 5.2 之后的版本,加入了 goto
这个关键字,用来控制程序跳转到指定 label
。我们可以利用这个特性,来模拟 continue 的实现。需要注意的是 goto
只能跳转到 label
,而 ::name::
的格式就可以设置一个 label
。
for i=1,5 do if i == 3 then goto continue
end print(i) ::continue::
end复制
这样就简单实现了 continue。但是有些同学可能会有疑问,这是 Lua 5.2 的特性,我们都知道 OR 中使用的 Lua 5.1,那如何使用?
其实我们只需要使用 LuaJIT 就可以解决这个问题了。在 LuaJIT 的主页上有这个介绍:
LuaJIT supports some language and library extensions from Lua 5.2. Features that are unlikely to break existing code are unconditionally enabled:
- goto and ::labels::.
也就是说 LuaJIT 把 5.2 的这个特性拿过来了。那我们来验证下:
继续验证 OR :
那么 goto
还有哪些玩法?还记得我们原来实现的尾递归优化不?当然也可以使用 goto
来实现:
然而感觉并没什么卵用。其他玩法需要各位同学自己去挖掘了。。不过需要注意的是 Lua 也有对 goto
的滥用限制:
A label is visible in the entire block where it is defined (including nested blocks, but not nested functions).
A goto may jump to any visible label as long as it does not enter into the scope of a local variable.