Problem with inheritance with Lua (attempt to call field 'String' (a nil value))

Viewed 613

I am having difficulties with Lua's inheritance. I am getting an error

"Error: main.lua:32: attempt to call field 'String' (a nil value)"

What am I misunderstanding ? I don't understand how my example differs from : https://www.lua.org/pil/16.2.html

Animal = {}

function Animal:New()
    a = {}
    setmetatable(a,Animal)
    a.__index = Animal

    return a
end

function Animal:String()
    print("I am an animal")
end

Cat = {}

function Cat:New()
    c = Animal:New()
    setmetatable(c,Cat) -- Set metatable to be Cat
    c.__index = Animal -- Inherits from Animal

    return c
end

-- Overwriting Bark
function Cat:String()
    print("I am a cat")
end


c = Cat:New() -- Should return a cat
print(c:String())
1 Answers

There are a few differences between your code and the example in PiL.

  1. Account.new uses self, not Account as the metatable for the new object. self might refer to Account or any subclass.

  2. Account.new sets the __index on self, not the new object. This is necessary, because metamethods must go on the metatable, not the object itself, to have any effect.

  3. SpecialAccount is created with Account:new(), not a plain, empty table. Note that that system uses the new method to create both subclasses and instances.

  4. SpecialAccount does not define a new method. It simply inherits the one from Account.

The error is due to the fact that c's metatable is Cat, but Cat has no __index. SpecialAccount's __index is set by its new method, when it creates an instance.

Related