For Loop not Looping

Hello, I tried to create a for loop to loop through the remaining players in a game if there were 2 or more players left. I have 2 players in the game though the for loop only looped once (No error message). I created the same for loop somewhere else in the script and a print statement inside printing the index number and it looped twice. Can someone please help?
I forgot to mention that plrs is a table.

if #plrs == 1 then
	-- Not the problem
	print("Only 1 survived")
	Survs.Value = plrs[1].Name
	ShowSurv.Value = true
	plrs[1].leaderstats.Survivals.Value = plrs[1].leaderstats.Survivals.Value + 1
	table.remove(plrs, 1)
elseif #plrs >= 2 then
	-- Problem below
	print(#plrs.." survived") -- Output: 2 survived
	for x, player in pairs(plrs) do
		if x == 1 then
			Survs.Value = plrs[1].Name
			print(Survs.Value) -- Output: Player1
		else
			Survs.Value = Survs.Value..","..plrs[1].Name
			print(Survs.Value) -- No output (Output supposed to be: Player1,Player2)
		end
		print(x) -- First loop: 1, No second loop
		plrs[1].leaderstats.Survivals.Value = plrs[1].leaderstats.Survivals.Value + 1
		table.remove(plrs, 1)
	end
	ShowSurv.Value = true
end

The same loop somewhere else:

for x, player in pairs(plrs) do
	print(plrs[x]) -- First loop: Player1, Second loop: Player2
end
1 Like

Because your loop just get the ‘Players’ service and not all the players, it’s maybe why.
So just remplace this:
for x, player in pairs(plrs) do

by this:
for x, player in pairs(plrs:GetChildren()) do

You can also use :GetPlayers() but me i usually use GetChildren().
I wish it helps you!

1 Like

I forgot to mention that plrs is a table. So plrs:GetChildren creates an error. But thanks for the suggestion!

Perhaps it has something to do with ’table.remove(plrs,1)’ being present as you’re attempting to iterate through the table?

1 Like

Yeah, doing table.remove(plrs, 1) is going to cause issues with your for loop.
I’d make a new table, add the players thats suppose to REMAIN in the new table. Then replace plrs with the new table, instead of removing from the old one.

1 Like

In replacement to table.remove(plrs, 1) and considering you never try to break the loop, after the loop itself, you can do

plrs = {}

Instead of

plrs[1] -- In your loop, use:
plrs[x] -- x is the index provided by the for-loop which you ignore.
1 Like

Thanks for the suggestion! It works now. :slight_smile:
image

1 Like

Here’s an optimized one.

	for x, player in pairs(plrs) do
		Survs.Value ..= (x ~= 1 and "," or "") .. player.Name;
		plrs[x].leaderstats.Survivals.Value = plrs[1].leaderstats.Survivals.Value + 1;
	end
	plrs = {};

This should do the same thing if I understood your loop correctly.

1 Like