Help with table 'sorting'

I’m trying to table.remove certain instances from a table from within a for loop.

But when doing so, the length of the table changes, and in the end, some elements that meet the criteria for being removed aren’t actually removed.

--example:
--i want to remove any instance that is parented to workspace.Folder

local obj1 = workspace.obj1
local obj2 = workspace.Folder.obj2
local obj3 = workspace.obj3
local obj4 = workspace.Folder.obj4

local MyTable = {
    obj1,
    obj2,
    obj3,
    obj4
}

for Index,Value in ipairs(MyTable) do
    if Value.Parent == workspace.Folder then
        --table.remove(MyTable,Index)?
        --table.remove(MyTable,table.find(MyTable,Value))?
        --table.remove(MyTable,1)?
    end
end

What would be the way of doing this then?

1 Like
--example:
--i want to remove any instance that is parented to workspace.Folder

local obj1 = workspace.obj1
local obj2 = workspace.Folder.obj2
local obj3 = workspace.obj3
local obj4 = workspace.Folder.obj4

local MyTable = {
    obj1,
    obj2,
    obj3,
    obj4
}

for Index,Value in ipairs(MyTable) do
    if Value.Parent == workspace.Folder then
        table.remove(MyTable,Value)
    end
end

This script should search through MyTable, make sure Value is parented to workspace.Folder and then finally find Value inside of MyTable and remove it.

So it would be

table.remove(MyTable,table.find(MyTable,Value))

?

Since table.remove needs a table and a index

2 Likes

That’s wrong, the second argument of table.remove is a number which is the position of the value in the table, your solution will type error. The correct way is using table.find:

for index: number, value in ipairs(MyTable) do
	
	local pos = table.find(MyTable, value)
	
	if value.Parent == workspace.Folder and pos then
		table.remove(MyTable, pos)
	end
end
1 Like

This is correct, I forgot about table.find

1 Like

Could you add some comments on your codeblock explaining what each important line is doing?

I didn’t understand pos :confused:

The table.find function returns the index of the value in the table, if it is not in the table, returns nil. So it’s setting pos to a number which is the index of the object in the table.

for index: number, value in ipairs(MyTable) do -- Iterates over MyTable
	
	local pos = table.find(MyTable, value) -- Gets the index of the value in MyTable
	
	if value.Parent == workspace.Folder and pos then -- Checks if the value's parent is the folder, and if pos isn't nil
		table.remove(MyTable, pos) -- Calls table.remove to remove the value of the index pos from MyTable
	end
end
1 Like