Convert String to Instance?

Lets say you have a string like this:

local Dir = "workspace.Baseplate"

Is it possible to convert into “instance form”? Like this:

local Dir = workspace.Baseplate
3 Likes

You can use string.split() to divide the path into instance names, and then use a loop to go through them:

local dir="Workspace.Baseplate"
local segments=dir:split(".")
local current=game --location to search
for i,v in pairs(segments) do
current=current[v]
end
print(typeof(current)) --"Instance"

There may be a way to specify the very first location, but if there is, I’m not aware of it.

22 Likes

You could use string.split, with the separator being “.”, then use a FindFirstChild loop to go through it.

local function GetInstance(String)
	local Table = string.split(String, ".")
	local Service = game:GetService(Table[1])
	
	local ObjectSoFar = Service
	for Index, Value in pairs(Table) do
		if Index ~= 1 then -- Don't run over the service.
			local Object = ObjectSoFar:FindFirstChild(Value)
			if Object then
				ObjectSoFar = Object
			else
				break
			end
		end
	end
	
	return (ObjectSoFar ~= Service and ObjectSoFar) or nil
end

local Baseplate = GetInstance("Workspace.Baseplate")
5 Likes

If given the Instance, you can use :GetFullName() to return the ancestry of the part. Sadly this doesn’t really solve your problem as it works in inverse.

Why suggest it then?

GetFullName has little to no purpose in appearing in production code. At the very least, you may find yourself using it in debugging for some obscure cases where knowing the hierarchy is important for debug information. It has nothing to do with converting strings into DataModel paths.

This works too… (Crappy forum formatting aside) This is really the same thing as what ChipioIndustries script is doing. His script will work no matter how many “segments” there are in the string. In pairs is slower than just using a regular for loop though I think.

local myString = "Workspace.Part"
local strArray = myString:split(".")
local myInstance = game[strArray[1]][strArray[2]]
print(myInstance.Name)

local myInstance = game
for i = 1, #strArray do
    myInstance = myInstance[strArray[i]]
end

print(myInstance.Name)
2 Likes