Hi, I have been trying to learn loop breaking i kinda get but not 100% BUT I still get a little confused.
The break keyword breaks the innermost loop. I believe this is what you mean, if not please tell me. Because breaking is pretty self explanatory
Example
while true do
while true do
print("Innermost loop broken!")
break
end
print("Outermost loop not broken!")
end
Yeah, that’s it also why did you use 2 while do loops?
He used 2 while do loops in order to show you that if you use break, it will break the second loop and not the first, so in his case:
It will print “Innermost loop broken!” once, and since he breaks it, it will print “Outermost loop not broken!”
continuously
Oh ok thanks, Have a great day!
IF you want to break the entire loop, do something like this:
local breakCondition = false
while true do
while true do
print("Breaking the inner loop!")
breakCondition = true
end
if breakCondition then
print("Breaking the outer loop!")
break
end
end
What break does is skip to the end of the loop/exit the loop the break is in (the innermost loop).
Ex:
while true do
while true do
break -- 1
end
-- 1 That break will skip here
break -- 2
end
-- 2 will skip here
That checks if the variable isn’t equal to nil
- what you’re looking for is
if breakCondition == true then
or set
to nil.
Nope, it passes if the value is truthy (i.e., not false or nil). Comparing to a boolean is even worse practice, since it’s already a boolean. marfit’s code doesn’t even work anyways since the nested while loop prevents the if branch from executing
The if statement will never be reached because the inner while loop does not terminate. I get it’s for the sake of demonstration but this example’s sort of strange, especially considering you’re not using the conditional of the while loop when it could be used in all cases.
local breakCondition = false
while (true) do -- Non-terminating
while (breakCondition == false) do
breakCondition = true
end
if (breakCondition) then -- Not falsy
break -- Can just use the conditional though
end
end