For loop only loops through once?

I have 2 players in the table, inGame_Players. I want to loop through each player in the table to see if a value is still true, if it isn’t then remove them from the table. The function runs and removes the player from the table but then stops looping through. Any way to fix this?

for index, plr in pairs(inGame_Players) do
			print("looped through")
			if plr.InGame.Value == false then
				table.remove(inGame_Players, index)

So a pairs loop loops through the amount of indexes in a table right? I assume the “InGame” if statement is run when the player is leaving. So that means the player would be removed from the table and it would only have one index.

The function would have already ran once and if it checked again, it would see that the table has one index (not sure if it stores the ORIGINAL table but I doubt it because it probably would run again if it sorted the original one) and it has ran once already; so it would probably stop.

Your issue is occurring due to the nature of tables, the for loop is running through a single time and then removing an index from the table. Once this index is removed the other index takes its place as number 1 in the table thus making it so the for loop can only iterate once.

1 Like

That makes sense. I could just loop through the game.Players and check if they’re in the table and if their value is false, then remove them.

I believe it may help you to opt in for a different approach to this by using the Players class events to check for players joining and leaving as well as creating tables.

This would certainly fix your issue, hope you figure it out and have a great day!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.