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
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.
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.