# Problem with a while loop

Let’s say I’ve got a big while loop, and I want to stop that loop at any part in the code. I’ve tried doing it myself, but idk what to do to make that work. I’ve looked around the devforum for help, but that didn’t work. I don’t know how to go about doing this.

If you want to break out of a loop before it’s finished, without restarting the loop, you will have to use the break keyword. It does what it says - breaks the loop, causing it to finish early.

Let’s see it in action. Pretend we have a script as shown, which prints all the numbers between 1 and 15.

x = 0
while x <= 15 do
x = x + 1
print(x)
end

If we wanted to make it stop at 10, we could simply change x <= 15 to x <= 10. There is another way to achieve this though (all though I would’t recommend using it in this situation). Using the break keyword, you can stop the loop.

x = 0
while x <= 15 do
x = x + 1
print(x)
if x >= 10 then
break
end
end
2 Likes

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