Replies: 1 comment 1 reply
-
Did some testing and composition does in fact resolve the issue, although it's a completely different OOP model and probably isn't the best solution considering standard Lua practices local interface Parent
name: string
metamethod __index: ParentMT
end
local interface ParentMT
new: function(self: ParentMT, name: string): Parent
greet: function(self: Parent)
__index: ParentMT
end
local ParentClass: ParentMT = {}
ParentClass.__index = ParentClass
function ParentClass:new(name: string): Parent
local instance: Parent = setmetatable({}, {__index = self})
instance.name = name
print("Parent constructor: " .. name)
return instance
end
function ParentClass.greet(self: Parent)
print("Hello, my name is " .. self.name)
end
local interface Child
parent: Parent
age: number
metamethod __index: ChildMT
end
local interface ChildMT
new: function(self: ChildMT, name: string, age: number): Child
greet: function(self: Child)
greetWithAge: function(self: Child)
__index: ChildMT
end
local ChildClass: ChildMT = {}
ChildClass.__index = ChildClass
function ChildClass:new(name: string, age: number): Child
local instance: Child = setmetatable({}, {__index = self})
instance.parent = ParentClass:new(name)
instance.age = age
print("Child constructor: " .. name .. ", " .. age)
return instance
end
function ChildClass.greet(self: Child) -- Optional, could just call child.parent:greet()
ParentClass.greet(self.parent)
end
function ChildClass.greetWithAge(self: Child)
print("Hello, my name is " .. self.parent.name .. " and I am " .. self.age .. " years old")
end |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
It's common for subclasses to have incompatible constructors as they might require more information. As the constructor isn't available on the instance it can be incompatible without causing issues
Example:
In lua however since there are no classes the constructor is just a normal function
In base Lua you can do something similar just fine
However in teal, as the constructors are incompatible and they are treated as regular methods, this just isn't possible
Is there a way to type this correctly? Do I have to do inheritence Rust style? Do I seperate the constructor from the metatable?
Beta Was this translation helpful? Give feedback.
All reactions