Specifically, When should i use metatables? and at what case do i really need to use it?

I have scrolled through maaany countless post about this yet I still can’t really find a solution about this!!. Metatables are indeed powerful and make tables stronger, however i’m not so sure on what im going to use it on.
Any help would be appreciated!!

Let’s say we have a table, Vehicle. And it has a function ,new, which creates a new instance of Vehicle. That instance should have all the same functions as Vehicle, right? So, whenever we try and call a function of Vehicle on an instance of vehicle, we should look at Vehicle, to see if it’s there. For that, we use __index.

local Vehicle = {}
Vehicle.__index = Vehicle --[[ Whenever something is indexed, if it can not be found on the table itself, it'll see if it can find it on the table which it indexes to. 
In this case, the table is the Vehicle table. This makes sense because any table that inherits from Vehicle, when indexed will index back to Vehicle.
]]
function Vehicle.new(number_of_seats : number, size : Vector3)
	local self = setmetatable({}, Vehicle) 
	
	self.number_of_seats = number_of_seats
	self.size = size
	
	return self
end

function Vehicle:spawn(position : Vector3)
	local part = Instance.new('Part')
	part.Size = self.size or Vector3.new(4,4,4)
	part.Anchored = true
	part.Position = position
	part.Parent = workspace
	if self.part then
		self.part:Destroy()
		self.part = part
	end
end

local myCar = Vehicle.new(4, Vector3.new(10,4,4))
myCar:spawn(Vector3.new(0,5,0)) -- we use Vehicle's spawn function. 

So now, when we create a new vehicle using Vehicle.new, we can spawn it in the world.

2 Likes