I’m struggling with a nuance of OO and inheritance in Codea. I have the code below, which given my understanding should function correctly:
--# Main
function setup()
local base = Base()
base:incrementIntMember()
print("----")
local derived = Derived()
derived:incrementIntMember()
end
--# Base
Base = class()
function Base:init()
print("In Base:init()")
self.i = 1
end
function Base:incrementIntMember()
print("In Base:incrementIntMember()")
self.i = self.i + 1
end
--# Derived
Derived = class(Base)
function Derived:init()
print("In Derived:init()")
Base:init(self)
-- Also doesn't work
--Base:init()
end
However, when I run it it gives the following output:
In Base:init()
In Base:incrementIntMember()
----
In Derived:init()
In Base:init()
In Base:incrementIntMember()
error: [string "Base = class()..."]:10: attempt to perform arithmetic on field 'i' (a nil value)
Pausing playback
It’s not clear to me why ‘self.i’ is nil in the case where the object being called derives from the base. The base class’ constructor (init) is being called from the derived class’ constructor so ‘self.i’ is initialized. I’m guessing that perhaps there are two ‘selfs’ in this situation (one for the base part of the object and one for the derived part) but that is counter to my experience in other languages…
Any enlightenment would be appreciated!