Lua模拟面向对象示例分享

代码很简单,这里就不多废话了,大家主要看看思路

function class(super)
    local mt = {__call = function(_c, ...)
        local function create(_c, _o, ...)
            if _c.__super then create(_c.__super, _o, ...) end
            if _c.__ctor then _c.__ctor(_o, ...) end
            return _o
        end
        local _o = create(_c, {}, ...)
        return setmetatable(_o, _c)
    end}
    mt.__index = super or mt
    return setmetatable({__super = super}, mt)
end
----------------------------------------------------------------------
A = class()
function A:__ctor(s)
    self.i = 123
    self.j = 333
    print('A ctor', s)
end
local a = A('a')
print(a.i, a.j)
-- B继承A
B = class(A)
function B:__ctor(s)
    self.i = 444
    print('B ctor', s)
end
local b = B('b')
print(b.i, b.j)

示例截图

以上就是本文的全部内容了,希望大家能够喜欢。