# How do I break a for i loop?

In my murder game I have a while true do to handle all of the rounds, thing is inside of those while true do im doing

for i = 10,1,-1 do

end

I want this loop to stop if everyone dies, I already made that but how do I make the for i loop stop? Btw idk if break works in for i loops but what if it breaks the while true do loop

6 Likes

Don’t worry, `break` works in `for i loops` and it won’t break the `while true do loop`.

6 Likes

I understand that when doing

local var = 5
local var = 3
print(var)
it will print 3 because that’s the closest so will break, destroy the closest for i loop?

1 Like

Add a condition inside the loop checking if everyone is dead or not and then breaking the loop.

``````for i = 10,1,-1 do
print("Round Ending")
break
end
end
``````
3 Likes

What you could do is create a bool Value and if all the players have died make the value true

then in the for loop you can add an if statement
so if Bool.Value == true then
break

1 Like

Not necessary the closest. For example:

``````for i = 10, 1, -1 do
-- random code
-- random code
-- random code
-- random code
-- random code
if i == 1 then
break -- this will not stop the loop below but instead, stop the loop it is inside, which is the loop above
end
for a = 230, 30, -1 do

end
end
``````

But if you mean the closest in the sense that it checking the closest above, then yeah, you’re correct.

9 Likes

3 Likes

You need to have some sort of indication about players’ life status. You can’t just listen to the “Died” event, as players will respawn in the lobby. So, have a bool value called “Playing” inside every player. Set it to true when a game starts, and false when the player dies.

To make the loop break, check the Playing value of every player after every cycle. Like:

``````for i = 1, 10 do
for _, Player in pairs(Players:GetPlayers()) do
if Player.Playing.Value then
break
end
end
break
end
end
``````
5 Likes

1 Like

You should post the solution and mark it as the solution then, so others with the same problem know where exactly to look.

1 Like
``````for i = 1, 10 do
local PlayersAlive = 0
for _, Player in pairs(Players:GetPlayers()) do
if Player.Playing then
PlayersAlive = PlayersAlive + 1

end
end