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
::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
::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
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