Lua Break and Goto
Break is a statement that leaves the innermost loop at once. Lua also uses goto with a label to skip the rest of one pass.
Break stops the count at 4
The loop plans to count to 10. Break at 4 ends it early, so only 1 to 3 print.
for i = 1, 10 do
if i == 4 then
break
end
print(i)
end
print("Stopped")Search until the target is found
The count climbs one by one. Break leaves the loop the moment the target matches.
local target = 7
local n = 1
local attempts = 0
while true do
attempts = attempts + 1
if n == target then
break
end
n = n + 1
end
print("Found " .. target .. " in " .. attempts .. " attempts")Skip even numbers with goto
Even values jump to the label at the end of the body. Odd values reach the print line, so only 1, 3, and 5 print.
for i = 1, 6 do
if i % 2 == 0 then
goto continue
end
print(i)
::continue::
endExample
for ticket = 1, 8 do
if ticket == 2 or ticket == 4 then
goto continue
end
print("Draw " .. ticket)
if ticket == 6 then
print("Winner: " .. ticket)
break
end
::continue::
endKey points
- Break: the loop ends right away, and code after the loop runs next.
- Innermost loop: break leaves only the loop that holds it.
- No continue: Lua has no continue keyword.
- Goto label: a label marks a place that goto can jump to.
- Continue pattern: a ::continue:: label at the end of the body plus goto continue skips the rest of a pass.
In this example, the loop draws tickets from 1 to 8. Tickets 2 and 4 jump to the continue label, so they never print. Ticket 6 prints its draw line, then prints the winner line and break ends the loop.
Note
keep goto small and clear, and use it for this skip pattern.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does break do inside a loop?