在 Lua 中,goto 语句允许将控制流程无条件地转到被标记的语句处。
goto Label
其中 lable 的形式为:
:: Label ::
使用 goto 语句,可以直接跳转到指定的标记处。
使用 goto 语句,实现程序跳转
#!/usr/bin/lua
print("haicoder(www.haicoder.net)\n")
local a = 1
::label:: print("--- goto label ---")
a = a+1
if a < 3 then
goto label -- a 小于 3 的时候跳转到标签 label
end
程序运行后,控制台输出如下:
我们使用了 goto 实现了如果 a 小于 3 就跳转到 lable 的位置。
使用 goto 语句,实现 continue 语句的功能
#!/usr/bin/lua
print("haicoder(www.haicoder.net)\n")
for i=1, 3 do
if i <= 2 then
print(i, "yes continue")
goto continue
end
print(i, " no continue")
::continue::
print([[i'm end]])
end
程序运行后,控制台输出如下:
我们使用了 goto 语句实现了 continue 的功能。
在 Lua 中,goto 语句允许将控制流程无条件地转到被标记的语句处。