Table.remove() breaking a for i,v loop?

This breaks after table.remove() calls once. No idea why it does, and I don’t remember table.remove() ever breaking loops before.

local HitEnemies = workspace:GetPartBoundsInBox(CF, Size, OP)

for i,Enemy in pairs(HitEnemies) do

	if (Stage.Type == "Ground") and (Enemy.Traits:GetAttribute("Flying")) or (Enemy.Traits:GetAttribute("Summon")) then
		
		table.remove(HitEnemies, table.find(HitEnemies, Enemy))
	
	end
	
end	

The if-statement is not the issue. The loop legit just stops after table.remove() does anything.

removing items from a table while iterating over it causes some items to be skipped over. you can prevent this by iterating over the table backwards

someone had a similar problem here

4 Likes

Somehow I’ve never ran into this, but thank you for the solution. It works very good. :+1:

Just adding on, it’s also redundant to call table.find during an iteration when you’re already given the index of the value you’re trying to remove - substitute it with the i variable, otherwise you’re running two iterations to remove it, one with the generic for that you’re already doing and the other that table.find does.

2 Likes

Realized this later on, I completely forgot about it lmao

1 Like

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