lua中子类如何调用父类方法


前言

在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字段实现链式调用。
  • 元表设置:确保实例和类的元表正确指向,实现方法查找链。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值