My Custom Function Not Working?

I want to achieve my custom function.

When I try to assign it to a variable the variable stays nil instead of making it the function.

I have went on devforum.roblox.com and youtube.com

My custom function “CreateInstance” allows me to assign it to a variable but when I do the variable still stays nil instead of making it into an instance.new / object so I am very confused I would be grateful for any help.

--ModuleScript function
function functionMod:CreateInstance(instancePart,class,parent)
	
	instancePart = Instance.new(class)
	
	if instancePart:IsA(class) then
		instancePart.Parent = game:FindFirstChild(parent)
		print(instancePart.Name .. " Was Created " .. " In: " .. tostring(parent))
	elseif not instancePart:IsA(class) then
		instancePart.Parent = nil
		warn(class .. " Is Not a Valid Class")
	end
end

--ServerScript
local funcMod = require(script.Parent.FunctionModule)

local part
part = funcMod:CreateInstance(part,"Part","Workspace")

Sorry for not much detail couldn’t add any really.

you could try using return and return the instancePart like this:

function functionMod:CreateInstance(instancePart,class,parent)
	
	instancePart = Instance.new(class)
	
	if instancePart:IsA(class) then
		instancePart.Parent = game:FindFirstChild(parent)
		print(instancePart.Name .. " Was Created " .. " In: " .. tostring(parent))
        return instancePart
	elseif not instancePart:IsA(class) then
		instancePart.Parent = nil
		warn(class .. " Is Not a Valid Class")
	end
end
1 Like

Maybe try this?

function functionMod:CreateInstance(class,parent)
	local success, result = xpcall(function() -- pcall the function
        return Instance.new(class) -- create the part and return it back
    end, warn) -- if something went wrong such as the class does not exist then call warn

    if success then -- check if it was successful
        result.Parent = game:FindFirstChild(parent) or workspace --[[ parent the object,
        if the parent is not put into the arguments then
        automatically put it into workspace]]
        return result -- return our part
    end
end

--ServerScript
local funcMod = require(script.Parent.FunctionModule)
local part = funcMod:CreateInstance("Part")

Also made some changes to your code.