How do I wrap instances to create custom methods to that instance?

Just like the title says, how do I wrap instances to create custom methods to that instance?

Here’s an example of what I’m trying to do:

local wrappedPart = wrap(workspace.myCoolPart)

wrappedPart:WaitForChildOfClass("Script")

It would be great if you could help! :slight_smile:

I’ve tried learning it myself but haven’t actually tried it so I’ll link the post that I learned from:

it’s just a bunch of metatable magic really

In addition to the link posted prior to this, I also did something like this a few years ago

I want to make a module for it and make it supportive for all instances

You could create a new wrapped instance class like this:

local WrappedInstance = {}
WrappedInstance.__index = WrappedInstance

function WrappedInstance.new(instance: Instance)
	local self = setmetatable({}, WrappedInstance)
	self.Instance = instance
	return self
end

function WrappedInstance:DoSomething()
	print("Doing something with " .. self.Instance.Name)
end

-- You can add any function you want

return WrappedInstance

And you can use it like this:

local WrappedInstance = require(Path.To.WrappedInstance)

local myWrappedPart = WrappedInstance.new(Instance.new("Part")) -- you can wrap any instance you want
myWrappedPart:DoSomething()

myWrappedPart.Instance:FindFirstChildOfClass("Script") -- can still access instance properties!
2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.