Elements removed with table.remove reappearing

I have this code that gets tagged parts within a radius, the problem being that, even though the parts are removed from the table, the removed parts show up in the table when outside the scope.

local Cubes = require(game.ServerStorage.CubeModule)
local Info = require(script.Parent.TowerInfo)
local Tower = script.Parent
local Projectile = game.ReplicatedStorage.Laser.LaserProjectile 
local TowerStats = Info.Stats
local TowerColors = Info.Colors
local NoHeightVector = Vector3.new(1,0,1)

while task.wait(1 / TowerStats.FireRate) do
	local Range = TowerStats.Range
	local TowerCFrame = Tower:GetPivot()
	local CubeList = workspace:GetPartBoundsInRadius(TowerCFrame.Position , Range)
	
	for i , part in ipairs(CubeList) do
		if game.CollectionService:HasTag(part , "Cube") == false then
			table.remove(CubeList , i)
		end
	end
	
	print(CubeList)
	
	table.sort(CubeList , function(A , B)
		return (A.Position - TowerCFrame.Position).Magnitude < (B.Position - TowerCFrame.Position).Magnitude
	end)
	
	if #CubeList > 0 then

		Tower:PivotTo(CFrame.lookAt(TowerCFrame.Position * NoHeightVector , CubeList[1].Position * NoHeightVector))
		
		if CubeList[1].Parent.Name ~= "CubeCache" then
			Cubes.CubeCache:ReturnPart(CubeList[1])
		end
	end
end

(btw I am using a custom framework for the :ReturnPart() function, But that is uninportant, or so i believe)

this is a really easy problem that I struggled with too, table.remove is kind of weird in that sense, the issue is that when your removing a part in the ipairs loop it shifts things downwards, i can’t explain it that well but heres an example

you can fix it by looping with a repeat loop


local i = 0
repeat
     i += 1
     local Part = CubeList[i]
     if game.CollectionService:HasTag(part , "Cube") == false then
	  table.remove(CubeList , i)
          i -= 1
     end
until i == #CubeList

if we find a cube in the list then we make the i value -= 1 (essentially going back to check the block we missed)

2 Likes