Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

Converting a string hierarchical to object hierarchical?

Asked by
tomgie 7
7 years ago

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

Log in to vote
1
Answered by 7 years ago
Edited 7 years ago

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.

Ad

Answer this question