break
causes any loop (repeat
, for
, while
) to stop; execution immediately skips to the point after the loop.
This is convenient when you know you are done working half way through a loop. It can also be used to increase efficiency to avoid computing extra, unnecessary later iterations.
Several examples on the wiki with break
Here's a simple example:
Find the first triangular number after 1000:
local sum = 0; for i = 1,1000 do sum = sum + i; if sum > 1000 then break; end end print(sum); -- 1035
Without the break, it would have kept computing up until the 1000th iteration. At that point, sum
would have been 500,500, which isn't what we're looking for. Since we're using this for
loop, there isn't really a straightforward way to figure out when the loop should stop without using break
.
In a loop if you put break it would stop the loop right then, and there. No questions asked.
while true do break print("hi") end
it wouldn't print hi.