I created a script to generate a maze and it works as expected but during coding, I discovered I should create object instances differently, so I refactored this:
local Cell = {
index = nil,
coordinates = Vector2.zero,
wasVisited = false,
markAsVisited = function (self)
self.wasVisited = true
end,
new = function(self, index: number, coordinates: Vector2)
local cell = table.clone(self)
cell.index = index
cell.coordinates = coordinates
return cell
end,
}
return Cell
to
local Cell = {
index = nil,
coordinates = Vector2.zero,
wasVisited = false
}
function Cell:new(index: number, coordinates: Vector2)
local instance = setmetatable({}, self)
self.__index = self
self.index = index
self.coordinates = coordinates
return instance
end
function Cell:markAsVisited()
self.wasVisited = true
end
return Cell
and instead of
I get
can someone explain to me why?


Lua doesn't have classes, where you can use a constructor to create a new instance of a type. But, being a flexible language, we can achieve something like classes through clever use of metatables. So let's talk for a moment about how the
__indexmetamethod works.When you ask a table for a key that doesn't exist, it will return
nil. But, if you set the__indexproperty to another table, the lookup will fall-through to that table.In this example,
bdid not become a clone ofawith all of its properties, it is still a table with onlybardefined. If you were to ask forfoo, since it does not find it inbit then checksato see if it can find it there. Sobis nota, but it can act like it.Let's look at what your code is doing :
As you can see, your code is struggling to define copies of Cells because your constructor is constantly overwriting the values in the original Cell table, not assigning them to the newly created instance. Each new instance is able to access these fields and not fail, but they are always referencing the last values set.
So, to fix it, here's what I would do :
Cell:newand change them all toCell.new