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.

8 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
   if everyoneIsDead then
       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

I already made the system… Just asking if it will break the while true do

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
    -- Your code
    local EveryoneDead = true
    for _, Player in pairs(Players:GetPlayers()) do
        if Player.Playing.Value then
            EveryoneDead = false
            break
        end
    end
    if EveryoneDead then
        break
    end
end
5 Likes

I already made the system again… I did that

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.

2 Likes
for i = 1, 10 do
    -- Your code
    local PlayersAlive = 0
    for _, Player in pairs(Players:GetPlayers()) do
        if Player.Playing then
            PlayersAlive = PlayersAlive + 1
            
        end
    end
    if EveryoneDead == 0 then
        break
    end
end

thats what would u do btw

2 Likes

oh well in that case @Tommybridge is correct

2 Likes