Unexpected behavior from a "for index, v in (table) do loop"

Background Info: I am making a class/module script for lobby creation in my tower defense game.

Here is the current loop code; (print spam for debugging)

print(self.Players)
for index, plr in (self.Players) do
	table.remove(self.Players,index)
	print(index)
	plr.Character:SetPrimaryPartCFrame(self.PortalPart.OutAttachment.WorldCFrame)
	print('teleported '.. plr.Name)
			
	print('Removed ' .. plr.Name)
	game.ReplicatedStorage.LobbyGui:FireClient(plr, "left")
	print('left ' .. plr.Name)
end

and here is the result:

20:06:26.835 ▼ {
[1] = Player1,
[2] = Player2
} - Server - LobbyModule:53
20:06:26.837 1 - Server - LobbyModule:56
20:06:26.837 teleported Player1 - Server - LobbyModule:58
20:06:26.838 Removed Player1 - Server - LobbyModule:60
20:06:26.838 left Player1

I expect the loop to go through every player, as the script even recognizes there are multiple players in the same table. I have no idea what’s causing it to only iterate once. Any ideas would be greatly appreciated.

What I’ve tried:

  • using in pairs(table)
  • google lol

Its funny how google will give a completely different result based off what you search.
My answer was solved in a related post:

2 Likes

Glad my solution could help you!

1 Like

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