Leaving a Loop Early with break
A loop checks its condition once per round. Sometimes you learn in the middle of a round that the loop should stop now. For example, you were searching for something and you just found it. The break statement ends the loop at once:
for i = 1, 10 do
if i == 4 then
break
end
print(i)
end
print("stopped")
Output:
1
2
3
stopped
The loop was set up for 10 rounds. In round 4, break ran, so the loop ended before print(i). The program went on with the first line after the loop's end. break works the same way in while and repeat loops.
Loop until a stop value
break is often used with while true. On its own, while true would loop forever, because its condition never becomes false. A break inside it is the way out. This program reads numbers until it reads a 0. It gets the input 4, 7 and 0, one per line:
while true do
local n = io.read("n")
if n == 0 then
break
end
print("Got " .. n)
end
print("Done")
Output:
Got 4
Got 7
Done
This shape is useful when you only know whether to stop after some work in the middle of the round, here after reading the number.
There is no continue
Many languages have a continue keyword that skips to the next round. Lua does not have it. If you write continue, Lua stops with a syntax error. Instead, put the work inside an if, so it runs only in the rounds you want:
for i = 1, 6 do
if i % 2 == 0 then
print(i)
end
end
Output:
2
4
6
In other people's Lua code you may also see goto continue. goto jumps to a label, here ::continue:: at the end of the block:
for i = 1, 6 do
if i % 2 == 1 then
goto continue
end
print(i)
::continue::
end
Output:
2
4
6
Both loops print the same numbers. The if version is easier to read, so use it in your own code.
Try to keep one break per loop. Each break is another way out of the loop, and a reader has to find all of them to understand it.
In the exercise, find the first number whose square is bigger than the target, print it, and stop with break.