How to transfer all methods and property of an object to another metatable?

So I want to create a new animation track object, that retains all the previous methods and properties and events of a normal animation track, but with additional methods coded by me. But how do I set a meta table of an instance onto a new table?

You can create a wrapper class. You can search through the DevForum for detailed explanations on them. Here is a bare-bones example:

local Wrapper = {}

function Wrapper.new(instance)
	local self = {}
	self._Instance = instance
	
	-- add properties
	self.MyValue = 0

	return setmetatable(self, Wrapper)
end

function Wrapper:SayHello()
	print("Hello, my name is " .. self._Instance.Name .. " and my value is " .. self.MyValue .. '!')
end

function Wrapper:__index(key)
	local value = Wrapper[key]
	
	if not value then
		value = self._Instance[key]
		-- you can also wrap the values, but I did not in this example
		
		if typeof(value) == "function" then
			local method = value
			
			value = function(self, ...)
				return method(self._Instance, ...)
			end
		end
	end
	
	return value
end

function Wrapper:__newindex(key, value)
	self._Instance[key] = value
end

function Wrapper:Destroy()
	-- clean up any other objects
	self._Instance:Destroy()
end

Using it on a part:

local part = Wrapper.new(Instance.new("Part"))
part.CFrame = CFrame.new(0, 5, 0)
part.BrickColor = BrickColor.Red()
part.Parent = workspace

part.Touched:Connect(function(otherPart)
	if otherPart.Parent and otherPart.Parent:FindFirstChild("Humanoid") then
		part:Destroy()
	end
end)

part:GetPropertyChangedSignal("Name"):Connect(function()
	part:SayHello()
end)

wait(3)

part.Name = "Bobby"

You can do a lot more with wrapper classes, but I mainly wanted to show the idea here.

1 Like

Thanks, I’ll look into wrapper classes more.