Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

What is break used for?

Asked by 10 years ago

What is break used for?

2 answers

Log in to vote
2
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
10 years ago

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.

Ad
Log in to vote
-1
Answered by 10 years ago

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.

Answer this question