Removed all table values except one, says table is nil

I have a function that gets a specific part from GetTouchingParts( ). It is supposed to print out the part that matches, and remove the ones that don’t from the table.

It prints out the match, but the entire table is empty on unpack. What’s going on here?

		
		local Parts = WaterPart:GetTouchingParts()
		

		for i,v in pairs (Parts) do
			if v.Name ~= Ball.Name then
				Parts[i] = nil
			
			else
				print(v)
			end
		end	
		
		print(table.unpack(Parts))
		
		return Parts
	end```
2 Likes

You could iterate backwards over the table, removing any values you don’t want.

for i = #Parts, 1, -1 do
	if Parts[i].Name ~= Ball.Name then
		table.remove(Parts, i)
	end
end

You could also construct a new table, with all the values you do want.

local FilteredParts = {}
for _, v in ipairs(Parts) do
	if v.Name == Ball.Name then
		table.insert(FilteredParts, v)
	end
end
3 Likes