Base Class Member Becomes Nil

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()
    local derived = Derived()

--# Base
Base = class()

function Base:init()
    print("In Base:init()")
    self.i = 1

function Base:incrementIntMember()
    print("In Base:incrementIntMember()")
    self.i = self.i + 1
--# Derived
Derived = class(Base)

function Derived:init()
    print("In Derived:init()")
    -- Also doesn't work

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!

I’m gonna guess you are using inheritance wrong, though I don’t really know.

I never use classes in lua, I find tables much easier to work with.

As far as I’m aware, when you call your base class’s initializer, you do so like this:

function Derived:init()

Note the use of ‘.’ instead of ‘:’.

Check out this thread for more examples.

Thanks @frosty that works (and makes sense to me too!).

obj:func(…) is syntactic sugar for obj.func(obj, …). So if you go base:init(self), what you really do is base.init(base, self)

Thanks @gunnar_z. I realized that as soon as I read @frosty’s answer. I could see that the ‘self’ in Base did not point to the instance of Derived but I was overlooking this important point (it’s obvious now, though - isn’t hindsight great!)