Best Solution: Getting an Ancestor with a Number as a suffix

Hi,

This is just something I’m wondering if its possible to do in lua, as well as the most efficient/best way of managing it.


For Example:

I have some Folder named House1, House2, House3, and House4.
Within those Folders, there is a multitude of objects in them, such as more Folders with way more Instances in them which a fraction have tags.
However I need to check whether they are an ancestor of these objects, I cant say :FindFirstAnscestor("House") because that sint their exact name, I cant say :FindFirstAncestorOfClass("Folder") as many of their ancestors will be folders.

Is this possible, and if so, what should I do?


NOTE: I’m not asking for code, because I know people are just going to paste code without explaining what it even does.

You could use the power of string patterns. With that in mind, all you’d have to do is match the name of each parent / ancestor with the pattern.

This pattern could be, for example, House%d+. Where House simply matches House, and %d+ matches any contiguous sequence of digits.

local myStr = "Folder123"

print(string.match(myStr, "Folder%d+"))
--> output: Folder123
-- because there WAS a match. Otherwise, it would be nil.
1 Like

Right, but I need to check the hirearchy of the Folder and to confirm whether its the ancestor, as they can be anywhere within the Folder.
it also requires you to have the first parameter in order to function, so im not sure where to go from there.

EDIT: The Objects im talking about are tagged, and can be anywhere.
Sorry If I’m confusing you.

1 Like

You could take inspiration from FindFirstAncestor’s (deduced) implementation. Let the code speak for itself:

local function findFirstAncestor(instance: Instance, name: Name): Instance?
    while instance do
        if instance.Name == name then
            return instance
        else
            instance = instance.Parent
        end
    end
end

In your case, instead of doing the check instance.Name == name, we could do string.match(instance, pattern).

2 Likes

An easy solution would be is have the main house folders like House7 be Configurations instead. Then you could just do

:FindFirstAncestorWhichIsA('Configuration')
3 Likes

A while loop is probably the best way to do this. Keep traversing up the hierarchy until you reach a parent whose name contains “House.” You might have to tweak the while loop conditional; I did not test the function at all.

local function GetHouseAncestor(instance)
	local parent = instance.Parent
	
	while parent ~= nil or parent ~= workspace do
		if string.find(parent.Name, "House") then
			return parent
		end
		
		parent = parent.Parent -- Move up to next parent
	end
end
1 Like

Thank you, it works pretty well.

Not very well for my sanity though (I had to rewrite most of my code :frowning_face: )

2 Likes

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