Table.remove breaking loop?

Hi guys, I’m working on a voting system, and I made a gamepass so players can vote double, but for some reason, table.remove is sort of breaking the loop :thinking:

for i,v in pairs(settings.Maps) do
   		for INDEX,TABLE in pairs(v.PlayersVoting) do
   			if (TABLE.Player == Player) then
   				print("FOUND PLAYER HERE AT MAP;",v.Name)
   				print("BEFORE;",v.PlayersVoting)
   				table.remove(v.PlayersVoting,INDEX)
   				print("AFTER;",v.PlayersVoting)
   			end
   		end
   	end

Output:
image

local t = {1, 2}
for i = 1, #t do
	table.remove(t, i)
end

print(#t) -- 1

This code is a simplified version of what you’re doing. To explain what’s happening I’ll expand out the for loop.

This code shows the same problem as before.

local t = {1, 2}
local i = 1
table.remove(t, i)
-- The table now looks like this: t = {2}
local i = 2 -- Here we're trying to refrence the 2nd number in the table.
table.remove(t, i) --  however, there's no 2nd number in the table because we've removed the first, bumping up the 2nd.

print(#t) -- 1

The problem is because we’re removing the 1st number, which will shorten the table, then we try to reference the second number which has become the first number.

Here’s two solutions:

  1. don’t remove each number individually, instead reset the table after going through them.

  2. Instead reference the 1st item and not the index in the loop.

table.remove(v.PlayersVoting, 1)
1 Like