Lua goto Statement
The goto statement in Lua allows the control flow to be unconditionally transferred to the labeled statement.
Syntax
The syntax is as follows:
goto Label
The format for 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 when a is less than 3
end
The output is:
--- goto label ---
--- goto label ---
As seen from the output, --- goto label --- is printed twice.
Example 2
i = 0
::s1:: do
print(i)
i = i+1
end
if i>3 then
os.exit() -- Exit when i is greater than 3
end
goto s1
The output is:
0
1
2
3
With goto, we can achieve 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
The output is:
1 yes continue
i'm end
2 yes continue
i'm end
3 no continue
i'm end