I found this tutorial: http://lua-users.org/wiki/InheritanceTutorial
I've got a metatable called Creature. Creature requires an argument in its constructor. The required argument is a string that represents the name.
local creature = Creature(name)
- Creature has a lot of other methods, like
getDescription()
. - Creature's
getDescription ()
returns a string: "This is a creature". - Creature's
getName ()
returns a string: the name
I want to create a new metatable (class) called Player
and have it inherit the Creature
metatable (class)
- The Player class will override only the getDescription () method.
- The Player class will also inherit the Creature's getName () method.
- Player's getDescription () returns a string: "This is a player".
I want to be able to do the following:
local creature = Creature("Bob")
print(creature:getDescription())
print(creature:getName())
local player = Player("Joey")
print(player:getDescription())
print(player:getName())
Should print:
This is a creature
Bob
This is a player
Joey
Basically, my issue is that the Creature class requires an argument to identify someone, a name. Its getName ()
function uses the value in the argument and prints it. If I am going to use Player to inherit all of the functions of Creature (and override if necessary), how do I change the code to make sure Player gets the argument it needs?
Code taken from the tutorial:
-- Create a new class that inherits from a base class
--
function inheritsFrom( baseClass )
-- The following lines are equivalent to the SimpleClass example:
-- Create the table and metatable representing the class.
local new_class = {}
local class_mt = { __index = new_class }
-- Note that this function uses class_mt as an upvalue, so every instance
-- of the class will share the same metatable.
--
function new_class:create()
local newinst = {}
setmetatable( newinst, class_mt )
return newinst
end
-- The following is the key to implementing inheritance:
-- The __index member of the new class's metatable references the
-- base class. This implies that all methods of the base class will
-- be exposed to the sub-class, and that the sub-class can override
-- any of these methods.
--
if baseClass then
setmetatable( new_class, { __index = baseClass } )
end
return new_class
end