How can I break this loop?

Hello, sorry for another relatively dumb question. I’m quite lost - I’m sure its a really simple answer and there is an easy way to do it. Sorry for the basic level question.

How can I break the first (red) loop if the second (green loop) gets broken by that if statement?

2 Likes

You can simply add a variable that gets set to true.

for n = 2, #waypoints do
     local nextPoint = workspace.points["Waypoint"..n]
     local Timer = workspace.DistributedGameTime + 5
     remotes.UpdatePosition:FireServer(nextPoint.Position)
     local BrokenLoop = false
     repeat wait()
          if workspace.DistributedGameTime > Timer then
               print("There was an issue with movement, server declined the request")
               BrokenLoop = true
               break
          end
          local dist = (nextPoint.Position - character.Position).magnitude
     until dist < 4
     if BrokenLoop then break end
end

edit: there may be some typos as I re-typed your code by hand. In the future, please paste your code in your post inbetween three Backticks (`) as so;

--Code Here

image

16 Likes

Thank you, and yeah - I didn’t think to include the code.
Really grateful that you took the time to write it out though, it works perfectly thank you.
Didn’t even think to add the variable

4 Likes

You could opt to use return instead of break as well, provided it won’t stop an external function prematurely (such as when this code is part of a longer function with code to execute below this)

> for i = 1,10 do 
 print(i) 
 if i == 5 then 
  repeat 
   if i == 9 then 
    return 
   end 
   i = i + 1 
  until i == 12 
 end 
end
1
2
3
4
5
> for i = 1,10 do 
 print(i) 
 if i == 5 then 
  repeat 
   if i == 9 then 
    break
   end 
   i = i + 1 
  until i == 12 
 end 
end
1
2
3
4
5
6
7
8
9
10

Alternatively you could check workspace.DistributedGameTime > Timer after the repeat-until loop and break from there again, that way no additional variables are required.

2 Likes