Lua 实现面向对象 进阶

class方法

function class(className, super, ...)
    local cla = {}
    if super and type(super) == "table" then
        for i,v in pairs(super) do
            cla[i] = v 
            cla.super = super
        end
    else
        cla = {ctor = function()end}
    end
    
    cla._cname = className
    cla.__index = cla
    
    function cla.new(...)					//新创建,实例化
        local ins = setmetatable({}, cla)
        ins:ctor(...)        				//构造函数
        return ins
    end
    return cla
end

基类

local a = class("a")

function a:ctor(name, value)
    self.name_ = name
    self.value_ = value
end

function a:printName()
    print(self.name_)
end

function a:printValue()
    print(self.value_)
end

子类

local b = class("b", a)

function b:ctor(name, value)
    b.super.ctor(self, name, value)
    self.name_new_ = name .. value
end

function b:printName()
    print("b-------------- printName")
end

function b:printNew()
    print("b------------- printNew ")
end

实例化

local c = b.new("name_b", "value_b")
c:printNew()			//子类新增方法,调用子类的printNew
c:printName()			//子类重载,调用子类的printName
c:printValue()			//调用父类printValue

运行结果

b------------- printNew 
b-------------- printName
value_b

lua 面向对象
Lua 实现面向对象 踩坑

你可能感兴趣的:(面向对象)