Difference between Break and Continue?

I have been looking at other posts, and i cant find anything about break or continue, its usually just asking about:

  • what is continue?
  • what is break?
  • Difference between break and return

Ya know, that kind of stuff,


But I was more of wondering the Difference between break and continue,
What do they do differently?

My First thought is that break is more abrupt, but I’m not sure.

2 Likes

break and continue statements are used in loops, while return can be used from either a loop body or function body. (assuming the loop is placed in a function body.)

break will break out of the loop immediately when executed.

continue will halt the current iteration of the loop, and will continue onto the next permitting the loop will not terminate on the next iteration.

return is for use with functions. A return statement will return some given value back to where the function was called from.

Examples of all three:

--//This causes the loop to end immediately after 'hello there' executes.
for i = 1, 5 do
print'hello there'
break
end
--//The continue statement causes the rest of the loop body to stop executing, so the loop moves onto its next iteration.
for i = 1, 10 do
if i % 2 == 0 then
continue
end

print'odd number found yessir'
end
local function getDiscount(age)

if age > 65 then
--//Senior discount is used
return .3
else
return 0 --//No discount is given
end
end

print(getDiscount(69)) --> prints .3 (or 30%)

A return statement can also just stop the function from executing all together, much like a break statement, causing no value to be returned to where it was called from. If return is used in a loop body, then again the same thing occurs and some value (or no value) is returned back to where the function was called from. This also causes the loop to break too obviously.

Hope this helps a bit :slight_smile:

20 Likes

So Pretty much: So you’re saying continue skips the Current iteration while break completely exits the loop?

2 Likes

That’s exactly right.

So continue does not necessarily mean the loop will terminate, only its current iteration, so no further statements in the loop’s body will execute.

break will completely terminate the loop upon its execution, moving down to any statements outside of the loop body.

3 Likes

Huh, well thats Interesting, Thanks!

3 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.