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

Converting a string hierarchical to object hierarchical?

Is there a way to convert a string hierarchical like "game.Workspace" to an object. I know there is game:FindFirstChild("Workspace") but how would I be able to do that when there is varying amounts of objects to do that for.

1 answer

✓ Accepted answer

Simple, just iterate the string with a pattern that matches everything that's not a period .. You can do this by using a complement character ^ inside of a character set []. Just throw that in the gmatch iterator to your for loop, and you're good to go. You should also define the ancestor you start searching, so you have a place to start.

local chain = "Part.Decal" -- path to desired object

-- You can define the container you're looking in, which will be the ancestor.
local function getObjFromChain(anc, str)
	local obj = anc -- new reference to ancestor to update it

	-- in order, go down path to desired object
	for objName in str:gmatch("[^.]+") do
		obj = obj[objName] -- update container
	end

	-- return last object in chain
	return obj
end

-- workspace would be the ancestor we're looking in, so we'll use that.
print(getObjFromChain(workspace, chain))

You could also use FindFirstChild instead of just trying to index the object for the next descendant, if you're not certain the object will be there. I assume you want this for deserializing an object? If you have any questions, just let me know.

Edit

In addition to the perfectly valid solution above, I also thought of a shorter version of it (if it interests you). You could just get the last set of non-period characters in the string, and use FindFirstChild with it's recursive feature. Example:

local chain = "Folder.Model.Part.Decal" 

local function getObjFromChain(anc, str)
	local objName = chain:match("[^%.]+$") -- every character except "." starting from end of string
	return anc:FindFirstChild(objName, true) -- return
end

-- Yields same result
print(getObjFromChain(workspace, chain))

Anyway, whatever suits your interests more I guess. I just thought that'd be a little bonus.

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