How would this object look like with metatables?

I avoid using metatables when writing objects because I haven’t fully grasped it yet, but I’m really looking to use it sometime in the future. The example below is a velocity object.

To anyone comfortable with metatables and OOP in general, how would this code look like if it uses metatables?

Thanks!

local VelocityObj = {}

function VelObj.new (Velocity, Acceleration, DirectionV, DirectionA, Position)
	local vobj = {
		Velocity = Velocity or 0,
		Acceleration = Acceleration  or 10,
		DirectionV = DirectionV or Vector3.new(0,1,0),
		DirectionA = DirectionA or Vector3.new(0,-1,0)
	}
	
	function vobj:Update(dt)
		return vobj.Velocity*vobj.DirectionV + dt*vobj.Acceleration*vobj.DirectionA 
	end
	
	function vobj:Run(f)
		assert(f, "No run function provided!")
		local t = os.clock()
		vobj.con = game:GetService("RunService").Heartbeat:Connect(function()
			local dt = os.clock()-t
			t = os.clock()
			f(vobj:Update(dt))
		end)
	end
	
	function vobj:Destroy()
		if vobj.con then con:Disconnect() end
		vobj=nil
	end
	
	return vobj
end

return VelocityObj 
local VelocityObj = {}

VelocityObj.__index = VelocityObj

function VelocityObj:Update(dt)
	return self.Velocity * self.DirectionV + dt * self.Acceleration * self.DirectionA 
end

function VelocityObj:Run(f)
	assert(typeof(f) == "function", "No run function provided!")
	local t = os.clock()
	self.con = game:GetService("RunService").Heartbeat:Connect(function()
		local dt = os.clock() - t
		t = os.clock()
		f(self:Update(dt))
	end)
end

function VelocityObj:Destroy()
	if self.con then
		self.con:Disconnect()
	end
	for p, _ in pairs(self) do
		self[p] = nil
	end
	setmetatable(self, nil)
end

function VelocityObj.new (Velocity, Acceleration, DirectionV, DirectionA, Position)
	local vobj = {
		Velocity = Velocity or 0,
		Acceleration = Acceleration  or 10,
		DirectionV = DirectionV or Vector3.new(0,1,0),
		DirectionA = DirectionA or Vector3.new(0,-1,0)
	}
	
	return setmetatable(vobj, VelocityObj)
end

return VelocityObj

When you construct an instance of VelocityObj, the result won’t contain any of the Update, Run, or Destroy functions. Rather, when you try to call them on the instance, it invokes the __index of it’s metatable and retrieves the ones in VelocityObj.

1 Like