Sense wrote: ↑Sat Mar 09, 2024 5:48 pm
Is there another one you’d recommend/are using?
I think that the mechanism being used to simulate this sort of templating / class inheritance (the __index metamethod from a metatable) is simple enough that you can reimplement it yourself, without the need for an entire library (unless you need the other parts from it of course).
For instance, from my personal utilities module, the class-like helper is this:
Code: Select all
local BaseObject = {}
function BaseObject._new(base, ...)
local t = setmetatable({}, base)
-- Run the init function if present, using the "instance" as self.
if base.init then
base.init(t, ...)
end
t.__index = t
t.__call = BaseObject._new
return t
end
function BaseObject.final(base, ...)
local t = setmetatable({}, base)
if base.init then
base.init(t, ...)
end
t.__index = t
t.__call = BaseObject._finalNew
return t
end
function BaseObject._finalNew(base, ...)
local t = setmetatable({}, base)
if base.init then
base.init(t, ...)
end
return t
end
BaseObject.__index = BaseObject
BaseObject.__call = BaseObject._new
setmetatable(BaseObject, {__call=BaseObject._new})
Used like this:
Code: Select all
local A = BaseObject()
function A:init(args)
print('A:init()', 'args:', args)
end
print('Creating instance of A...')
local B = A(123)
function B:init(args)
print('B:init()', 'args:', args)
end
print('Creating (final) instance of B...')
-- As I understand it, a final inheritance is one where you can't subclass
-- any more, just make instances from it.
local instance = B:final(456)
This mechanism is explained in these links:
-
https://www.lua.org/pil/13.4.1.html
-
https://www.lua.org/pil/16.html#ObjectSec
PS as it says in the PIL, another way to have tables following the same "interface" is to use a function where you organize all the common fields that they should have:
Code: Select all
local function method1(self, arg1, arg2)
...
end
local function method2(self, arg1, arg2)
...
end
local function createTemplate(instance)
instance = instance or {}
instance.myMethod1 = method1
instance.myMethod2 = method2
instance.valueA = 123
instance.valueB = 456
return instance
end
local instanceA = createTemplate()
local instanceB = createTemplate()
This should be
slightly faster than using that metatable mechanism, since it doesn't need the double-lookup (looking up the key on the "instance" table, not finding it, then looking it up on the __index table). In fact I'm thinking of going with this on some speed-critical code.