I am trying to make a role system using inheritance, so all roles inherit from RoleBase. RoleBase has an __eq metamethod to compare if 2 role objects are the same role. I have a demonstration of what I am trying to do:
-- role base
local RoleBase = {}
RoleBase.__eq = function(a, b)
print("Called Metamethod with ", a, b)
return a.id == b.id
end
RoleBase.__index = RoleBase
function RoleBase.new()
local self = setmetatable({}, RoleBase)
return self
end
-- end role base
-- dead
local Dead = {}
setmetatable(Dead, RoleBase)
Dead.__index = Dead
Dead.id = 1
function Dead.new()
local self = setmetatable(RoleBase.new(), Dead)
return self
end
-- end dead
-- testing
local a = Dead.new()
print(RoleBase.__eq)
print(Dead.__eq)
print(a.__eq)
print(a == Dead)
The prints at the end confirm that RoleBase, Dead, and a share the same __eq metamethod but it is not called when the code is ran.
RoleBase is created in the constructor for Dead local self = setmetatable(RoleBase.new(), Dead)
in the actual code, the RoleBase constructor actually does stuff
Since you are assigning different metatables for each inherited class, they will not work with the __eq metamethod. I would just use a regular .equals() method instead.
i had a :Equals method in rolebase because of this but it really bothers me that this equality check stands out like a sore thumb when everything else uses a == operator. itll be fine ig lol
Simply this style of implementing OOP will not allow you to do that. What you can do is to use another style. For example:
-- role base
local RoleBase = {}
local meta = {}
meta.__eq = function(a, b)
print("Called Metamethod with ", a, b)
return a.id == b.id
end
function RoleBase.new()
local self = {}
return self
end
-- end role base
-- dead
local Dead = {}
setmetatable(Dead, meta)
local deadId = 1
Dead.id = deadId
function Dead.new()
local self = setmetatable(RoleBase.new(), meta)
self.id = deadId
return self
end
-- end dead
-- testing
local a = Dead.new()
print(a == Dead)
Ok. apparently it is a reminiscence that luau has, inherited from lua5.1. In lua5.1 it is only required that the metamethods are the same. in its documentation it is explained in detail. But this is not consistent with the luau documentation mentioned above.
That’s why it still works.