Lua goto Statement
The goto statement in the Lua language allows the control flow to be unconditionally transferred to a labeled statement.
Syntax
The syntax format is as follows:
goto Label
The format of a Label is:
:: Label ::
The following example uses goto in a conditional statement:
Example 1
local a = 1
::label:: print("--- goto label ---")
a = a+1
if a < 3 then
goto label -- jump to label label when a is less than 3
end
::label:: print("--- goto label ---")
a = a+1
if a < 3 then
goto label -- jump to label label when a is less than 3
end
The output result is:
--- goto label --- --- goto label ---
As can be seen from the output result, it printed one extra time.--- goto label ---。
The following example demonstrates that multiple statements can be set in a label:Example 2
i = 0
::s1:: do
print(i)
i = i+1
end
if i>3 then
os.exit() --i is greater than3exit when
end
goto s1
::s1:: do
print(i)
i = i+1
end
if i>3 then
os.exit() --i is greater than3exit when
end
goto s1
The output result is:
0 1 2 3
With goto, we can implement the functionality of continue:
Example 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
The output result is:
1 yes continue i'm end 2 yes continue i'm end 3 no continue i'm endOther Extensions
Lua Loops