Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Why is my for loop not removing all of the items it should be in a table?

local Reg = MakeRegion(mouse.Target.Position)
	local Parts = workspace:FindPartsInRegion3(Reg,game.Players,math.huge)
	for i,v in pairs (Parts) do
		if mode == "ignoring" then
			if v.Color == ignoreColor then
				table.remove(Parts,i)
			end
		elseif mode == "target" then
			if v.Color ~= targetColor then
				table.remove(Parts,i)
			end
		end
	end

So the snippet of code above is supposed to remove all parts in the table that aren’t the color of targetColor when it is enabled, or are the color of ignoreColor when it is enabled. But for reasons I don't understand, when I print the length of the table at the end, it has only removed half and then stopped. Does anyone know why this is and what I could do about it?

1 comment

0

No problem!

1 answer

✓ Accepted answer

You cannot remove items from a table while looping through it. The only solution I can think of would be to create a new table, loop through the old table and only insert the items you want into the new table. Here is an example:

local function createNewTable(oldTable, mode)
	local newTable = {}
	if type(oldTable) == "table" then
		if mode == "ignoring" then
			for i,v in pairs(oldTable) do
				if not (v.Color == ignoreColor) then
					table.insert(newTable, v)
				end
			end
		elseif mode == "target" then
			for i,v in pairs(oldTable) do
				if v.Color == targetColor then
					table.insert(newTable, v)
				end
			end
		end
	end
	return newTable
end

I hope this helps and have a great day scripting!

1 comment

0

Thanks, this fixed it.

This discussion is preserved as it was. New answers, comments, and votes are closed.