前言
在Lua中,由于没有内置的类系统,子类调用父类方法需要显式引用父类并传递实例作为self参数。以下是具体实现步骤:
一、定义父类
Parent = {}
function Parent:new()
local instance = {}
setmetatable(instance, { __index = Parent }) -- 设置元表,实现方法查找
return instance
end
function Parent:sayHello()
print("Hello from Parent")
end
二、创建子类并继承父类
Child = Parent:new() -- 继承Parent的方法
function Child:new()
local instance = Parent:new() -- 创建父类实例作为基础
setmetatable(instance, { __index = Child }) -- 重设元表为Child
return instance
end
三、子类中调用父类方法
在子类方法中,直接通过父类表调用方法并传递self:
function Child:sayHello()
-- 调用父类方法
Parent.sayHello(self)
print("Hello from Child")
end
四、使用示例
local child = Child:new()
child:sayHello() -- 输出: Hello from Parent \n Hello from Child
方法解析
- 显式调用:通过Parent.methodName(self),将子类实例self传递给父类方法,确保父类方法能正确操作子类实例。
- 继承链:子类实例的元表指向子类,子类的元表指向父类,实现方法查找链。
使用super机制(可选)
若需更清晰的继承管理,可引入super字段:
function createClass(super)
local class = { super = super }
setmetatable(class, { __index = super })
class.__index = class
function class:new(...)
local instance = setmetatable({}, class)
if class.constructor then instance:constructor(...) end
return instance
end
return class
end
-- 使用示例
Parent = createClass(nil)
function Parent:sayHello() print("Parent hello") end
Child = createClass(Parent)
function Child:sayHello()
Child.super.sayHello(self) -- 通过super调用父类方法
print("Child hello")
end
总结
- 直接调用:适用于简单继承,通过Parent.method(self)直接引用。
- super链:适用于多层继承,通过维护super字段实现链式调用。
- 元表设置:确保实例和类的元表正确指向,实现方法查找链。