Skip to main content

Lua goto 语句

Lua 语言中的 goto 语句允许将控制流程无条件地转到被标记的语句处。

语法

语法格式如下所示:

goto Label

Label 的格式为:

:: Label ::

以下示例在判断语句中使用 goto:

示例 1

local a = 1
::label:: print("--- goto label ---")

a = a+1
if a < 3 then
goto label -- a 小于 3 的时候跳转到标签 label
end

输出结果为:

--- goto label ---
--- goto label ---

从输出结果可以看出,多输出了一次 --- goto label ---

以下示例演示了可以在 lable 中设置多个语句:

示例 2

i = 0
::s1:: do
print(i)
i = i+1
end
if i>3 then
os.exit() -- i 大于 3 时退出
end
goto s1

输出结果为:

0
1
2
3

有了 goto,我们可以实现 continue 的功能:

示例 3

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

输出结果为:

1   yes continue
i'm end
2 yes continue
i'm end
3 no continue
i'm end