lualove2d

How to extend classes in Lua


Use lib classic. I have next code:

Combination = Object:extend()

function Combination:new(level, score)
self.curentCombinationValues = 0
self.curentCombination = {}
self.level =  level
self.score =  score 
end

NonPair = Combination:extend()

function NonPair:new()
NonPair.super:new(1, 2)
end

OnePair = Combination:extend()

function OnePair:new()
OnePair.super:new(1, 3)
end

When I create two objects, the second one replaces the variables of the inherited object, which means the first one also changes.

local one = NonPair()
local second = OnePair()

one.level = second.level . Why?


Solution

  • NonPair.super:new(1, 2) is syntactic sugar for NonPair.super.new(NonPair.super, 1, 2) (the same pattern applies for OnePair).

    This means the contextual self inside Combination:new will not refer to the new instance (one), but rather the parent class itself (Combination). With this, self.level = level is then equivalent to Combination.level = level, setting a key-value pair on the class itself.

    The call to OnePair.super:new(1, 3) overwrites the values that were set by NonPair.super:new(1, 2), so both one.level and second.level result in the same value (both invoking the __index metamethod to find the value on the parent class).

    The correct pattern to use with this library is

    NonPair = Combination:extend()
    
    function NonPair:new()
      NonPair.super.new(self, 1, 2)
    end
    
    OnePair = Combination:extend()
    
    function OnePair:new()
      OnePair.super.new(self, 1, 3)
    end
    

    as shown in the README.