Description
Hey @mcclure maybe you can answer this. It's possible I've misunderstood how pl.class()
is supposed to work (it is under documented after all!), but with inheritance working properl now (thanks for that!) I'm on a mission to get rid of some of the ugly hacks I had in place in various projects.
I can get inheritance to work using the documented syntax (see foo
class below and the baz
subclass), but I was under the impression that another syntax should work too (see foo
class and bar
subclass). Unfortunately it does nothing at all.
Since that doesn't work as expected, one way I found to make subclassing convenient is using pl.tablex.update()
to populate the class after defining it as an exact copy of the parent class (see foo
+ qiz
below). Additionally I've used another syntax (see foo
+ zar
below) that works, but creates an extra degree of separation and (as of anything later than Penlight 1.8.0) now does not have a super()
method. I think this new behavior is correct –it shouldn't have one because there is a break in the inheritance since the constructor is given a plain table instead of a class— but still it leaves things in an awkward place.
Can you comment on why foo
+bar
doesn't work in the second example here?
local class = require("pl.class")
local tablex = require("pl.tablex")
local function subclass_hack (base, model)
return tablex.update(class(base), model)
end
local foo = class({
attr = "original base",
_init = function (self, arg)
print("Running init() from foo class with "..arg.." identifies as "..self.attr)
end
})
local bar = class(foo, nil, {
attr = "subclassed",
_init = function (self, arg)
self:super(arg)
end
})
local baz = class(foo)
baz.attr = "subclassed"
function baz:_init (arg)
self:super(arg)
end
local qiz = subclass_hack(foo, {
attr = "subclassed",
_init = function (self, arg)
self:super(arg)
end
})
local zar = class({
_base = foo,
attr = "subclassed",
_init = function (self, arg)
self._base._init(self, arg)
-- In Penlight <= 1.8.0 this worked:
-- self:super(arg)
end
})
-- Base class works as expected
local a = foo("1st")
-- This does *not* work as expected, it functions as an instance of foo
local b = bar("2nd")
-- This syntax works, its just cumbersome
local c = baz("3rd")
-- This hack to do what I expected pl.class to do in the bar class
local d = qiz("4th")
-- This gets the job done, but there is no super() function available
local e = zar("5th")
The output I get is:
Running init() from foo class with 1st identifies as original base
Running init() from foo class with 2nd identifies as original base
Running init() from foo class with 3rd identifies as subclassed
Running init() from foo class with 4th identifies as subclassed
Running init() from foo class with 5th identifies as subclassed
Obviously I expected the second line to be a subclass with different properties, not just a copy of the first class.