Lua模拟面向对象示例分享

本文这里主要给大家分享的是一则使用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)

示例截图

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

以上就是Lua模拟面向对象示例分享的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » Lua