Inheritance in Lua

Hi fellows corona SDK developers,

I am currently trying to implements inheritance with Beebe’s approach explained in his tutorial blogpost: Modular Classes in Corona found here: http://blog.anscamobile.com/2011/09/tutorial-modular-classes-in-corona/

I’m familiar at how using classes in corona, but soon as I try to implements inheritance, I am getting some unexpected errors.

In the comment section of his blogpost, fellow @Victor wanted to know how to implement inheritance, just like me. Jonathan gave him this answer:
@Victor: To make the dog class extend from that, in your dog.new() function, you’d set the table be an instance of animal, and also have whatever new properties that are specific to that dog. For example:

function dog.new()  
 local d = require( "animal" ).new()  
 d.name = "Rover"  
  
 return setmetatable( d, dog\_mt )  
end  

But, when I try this inheritance approach, I got an error while trying to call the numberOfLegs() methods.

I would like someone to look at my code and see what’s going wrong. Maybe Beebe’s approach is correct and I am just doing it wrong, but I want to know how I can implement inheritance in Lua the best way possible, possibly in line with Beebe’s approach tutorial…

Here I post the code from an easy and well commented example:

main.lua :

--Regular use of the base class animal.lua  
   
local animal = require("animal").new({  
 legs = " 4 legs !",  
 })  
  
  
--Call method numberOfLegs()  
animal:numberOfLegs() -- Output: The animal has : 4 legs !  
   
--Use of inherited class dog  
local dog = require("dog").new()  
   
--Call method getName()  
dog:getName() -- Output: His name is Rover  
   
--Call method numberOfLegs()  
dog:numberOfLegs() -- ERROR : attempt to call method 'numberOfLegs' (a nil value)  
--I should be able to call base methods from an inherited class...but it throws me an error...  

dog.lua (inherited from animal.lua) :

--Class dog  
   
local dog= {}  
local dog\_mt = { \_\_index = dog } -- metatable  
   
-- PUBLIC FUNCTIONS  
----  
   
function dog.new() -- constructor  
   
local dog = require( "animal" ).new({legs = " 4 legs !"})  
 dog.name = "Rover"  
  
 return setmetatable( dog, dog\_mt )  
   
end  
   
function dog:getName()  
 print("His name is " .. self.name)  
end  
   
   
return dog  

animal.lua (base class) :

[code]
–Class animal

local animal= {}
local animal_mt = { __index = animal } – metatable

– PUBLIC FUNCTIONS

function animal.new( params ) – constructor

local newAnimal = {
legs = params.legs,
hair = params.hair or false,
vertebrate = params.vertebrated or true
}

return setmetatable( newAnimal, animal_mt )

end


function animal:numberOfLegs ()
print ( “The animal has :” … self.legs )
end

return animal
[/code] [import]uid: 20617 topic_id: 25020 reply_id: 325020[/import]