Getting instance from string

This seems simple but it has somehow confused me, I want to find an instance using a string like so:

local part = "Part"
Teleport(part)

function Teleport(Item)
local part2 = game.ReplicatedStorage:FindFirstChild(part).Clone()
part2.Parent = workspace
end

The issue with this is that it cannot find the name of the part using the string variable. Is there a way around this?

2 problems.

  1. You can’t run the function before defining it, this isn’t like Java.
  2. You need a : for Clone, not .
local part = "Part"

function Teleport(Item)
local part2 = game.ReplicatedStorage:FindFirstChild(Item):Clone()
part2.Parent = workspace
end

Teleport(part)

I assume you meant to find “Item” not part, because I have no idea why else you would make that parameter.

I think i really need to get some sleep, yes I have been putting .clone this whole time for some reason, thanks

1 Like
local replicated = game:GetService("ReplicatedStorage")

local instance = "Part"

local function createInstance(instanceName)
	local foundInstance = replicated:FindFirstChild(instanceName)
	if foundInstance then
		local clonedInstance = foundInstance:Clone()
		clonedInstance.Parent = workspace
	end
end

createInstance(instance)

Just a couple more things, instead of indexing “game.ReplicatedStorage” each time the function is called it’s best to declare a non-local variable which is a reference to the “ReplicatedStorage” service, that way the service can be quickly referenced from within the function when necessary. If a function doesn’t need to be defined globally (without the local keyword preceding its definition) then declare it locally as I have done above, by doing this the function is integrated into the local environment which allows for it to be accessed when referenced much quicker than if it were global. Finally, you should check that “FindFirstChild()” did return a valid instance as calling the instance method “:Clone()” on a non-instance value will result in the script erroring.