A function to find all instances of specific objects within a given hierarchy

Hello guys, I’m working on a function that can find me specified objects inside an object, then return a table contains it.

I’ll go straight into the problem : The tables won’t merge up together.
I think the issue is on the code problem but I can’t find it out. It would be nice if you can spend sometime on this simple problem. Thank you!
— Find instances —

local function GetObjects(address,objname)
	
	local Table = {}
	
	for _,v in pairs(address:GetChildren()) do
		
		if v.Name == objname then
			table.insert(Table,v)
			print(Table)
		end
		if v:GetChildren() ~= nil then
			
			local subTable = GetObjects(v,objname)
			mergeTables(Table,subTable)
		end
		
	end
	return Table
end

— Merge Tables function —

local function mergeTables (tab1, tab2)
	
	for _,v in pairs(tab1) do
		
		table.insert(tab2,v)
		
	end
	return tab2
	
end

I think your mergeTables function is being passed a table inside a table.

1 Like

mergeTables(Table,subTable)
This returns a table but has no variable to contain it.
`local Table = mergeTables(Table, subTable)

1 Like

Wouldn’t this work?

local function getObjects(adress : Instance, objName)
local Table = {}

for _, v in pairs(adress:GetDescendants(true)) do
if v.Name == objName then
table.insert(Table, v)
end
end

return Table
end

1 Like

oh yea I forgot to pass it into a variable
Thank you for your answer!

Oh god, I forgot about GetDescendants too
Thank you for mentioning it! I’ll use this method

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