How would i go about turning a string into a reference?

I want to turn a string such as “Part.Child” into a usable reference to get to a specific “destination”

I dont want to use loadstring as i have been told it is unsafe and using brackets like
below doesnt work

local reference = "Part.Child"
print(workspace[reference])

just to clear things up, everything I am using this for is client sided.

how would i go about converting a variable like that into a reference?

I have seen people split the string into other strings and recursively go through it, but I think there has to be a more optimal way to do this.

1 Like

I believe you can only put the name of the child that you are looking for, not a path. You would have to do:

local part = "Part"
local child = "Child"
print(workspace[part][child])

As well as this, why would you need to do this in the first place? Can’t you just set a variable as an instance it use it from there?

1 Like

actually there is another way I can make my code work, but I am still interested in how i can turn a string into a reference.

1 Like

You could just split the string up by a given separator.

local function getByPath(root: Instance, path: string) -- in your case, 'path' is a string like `Part.Child`; 'root' would be the workspace
	for _, split in path:split('.') do
		root = assert(root:WaitForChild(split, 5), `Invalid path {path}! (got to {split})`)
	end
	
	return root
end
3 Likes