Need Help With an removing elements from a table via for loop

I have an array that contains player objects and I want to loop through the entire table to remove some player objects with a for loop, such as if the player or players get eliminated in a single cycle. I used the following:

for key, val in ipairs(attached) do
	if val and val.Character and val.Character:FindFirstChild("Humanoid") and val.Character.Humanoid.Torso then
			print(key, val)
			continue
		else
			table.remove(attached, key)
		end
end

The problem is, the first iteration that removes the correct player using the correct index causes the all of the higher indices of the table to shift down to fill in the gap, so when the next iteration comes through to remove another player, the index used to try to remove that player from the table might remove the wrong player or might not even exist anymore! How can I go about this? Is this just an inherent design flaw? Any suggestions on what I could do instead ? My premise may be wrong, so correct me if this presumption is wrong.

1 Like

You could do this

local shift = 0
for key, val in ipairs(attached) do
	if val and val.Character and val.Character:FindFirstChild("Humanoid") and val.Character.Humanoid.Torso then
			print(key, val)
			continue
		else
			table.remove(attached, key-shift)
            shift += 1
		end
end
2 Likes

Whoa, can you explain exactly how this works? It fixed my problem but I am having trouble seeing why. Is this solution going to work 100% of the time as well?

The code he provided is essentially making the

local shift 

Less than the iteration in the loop. So for example after it loops through the first time after removing, the arithmetic statement

key-shift

will get the preceding position for the next removal I believe that is what he changed and how it works. Hope it makes sense, I might not be the best in describing this scenario.

1 Like

If your issue is about shifting indexes, don’t use table.remove then because it does that and just manually set the index to equal nil

 -- table.remove(attached, key)
 attached[key] = nil
 -- this way indexes won't shift, if that's of any help within your current system

You’ll need to iterate in pairs then since ipairs can’t be used to index non-list items and indexes are verified to not be nil within its iterator function.

8 Likes