我找到了这个教程: http: //lua-users.org/wiki/InheritanceTutorial
我有一个名为 Creature 的元表。Creature 在其构造函数中需要一个参数。必需的参数是表示名称的字符串。
local creature = Creature(name)
- Creature 有很多其他方法,例如
getDescription()
. - Creature 的
getDescription ()
返回一个字符串:“这是一个生物”。 - 生物
getName ()
返回一个字符串:名称
我想创建一个名为的新元表(类)Player
并让它继承Creature
元表(类)
- Player 类将仅覆盖getDescription ()方法。
- Player 类也将继承 Creature 的 getName () 方法。
- Player 的getDescription()返回一个字符串:“ This is a player ”。
我希望能够做到以下几点:
local creature = Creature("Bob")
print(creature:getDescription())
print(creature:getName())
local player = Player("Joey")
print(player:getDescription())
print(player:getName())
应该打印:
这是一个生物
Bob
这是一个玩家
Joey
基本上,我的问题是 Creature 类需要一个参数来识别某人,一个名字。它的getName ()
函数使用参数中的值并打印它。如果我打算使用 Player 继承 Creature 的所有功能(并在必要时覆盖),我如何更改代码以确保 Player 获得所需的参数?
从教程中获取的代码:
-- 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