Whats going on here?

I am trying to make a team-based wave respawn system. If you die you must wait until at least 2 other teammates have died to respawn.

The playerlist currently prints out the 3 players that died
[1] Player1
[2] Player2
[3] Player3

However, when it goes to respawn the players for some reason it always skips the player in the middle. When I remove the line “table.remove(Team1Dead,i)” it respawns all 3 players normally. However, I need to be able to clear out the list of players who have been respawned. I am honestly stumped.

Just so you have some context, DeathEvent is called every time a player dies. The variable “playerName” is an instance of the player.

DeathEvent.OnServerEvent:Connect(function(playerName)

	local DeadPlayer = playerName
	
	if DeadPlayer.Team == Teams.Team1 then
		Team1.Tickets.Value = Team1.Tickets.Value - 1
		print("Team 1 Tickets:", Team1.Tickets.Value)
		
		table.insert(Team1Dead, playerName)
		print(Team1Dead)
		if #Team1Dead >= 3 then
			for i, v in pairs(Team1Dead) do
				
				v:LoadCharacter()
				table.remove(Team1Dead,i)
			end
		end
		
	else if DeadPlayer.Team == Teams.Team2 then
			Team2.Tickets.Value = Team2.Tickets.Value - 1
			print("Team 2 Tickets:", Team2.Tickets.Value)
			table.insert(Team2Dead, playerName)
			if #Team2Dead >= 3 then
				for i, v in pairs(Team2Dead) do
					
					v:LoadCharacter()
					table.remove(Team2Dead,i)
				end
				end
		else
			wait(1)
			playerName:LoadCharacter()
			print("no team")
		end
	end

The for loop, in your case, does the following: iterate from element number 1, then 2, then 3, and so on. When you remove element #1 from the table, the order of the elements in the table alters. That is, if you were to have a table {“a”, “b”, “c”}, the new table (thus the new order) would be {“b”, “c”}. In your for loop, however, removing the first element would not change the element number at the next iteration; removing the first element would still cause the for loop to iterate at element number 2, regardless of the current state of the table.

That’s why, when you remove the first element of {“a”, “b”, “c”} in the first iteration, the second iteration would remove element number 2, which would then be “c”, because the table would become {“b”, “c”} by the end of the first iteration. That leaves you with just {“c”}, because element number 3, then, wouldn’t exist, causing the for loop to terminate.

1 Like

Thank you I got it figured out now. I didn’t realize that it was changing the index on me.

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