--保存类类型的虚表 local _class = {} -- 自定义类型 ClassType = { class = 1, instance = 2, } function isA(class_type_child, class_type_parent) local now_super = class_type_child while now_super ~= nil do if now_super == class_type_parent then return true end now_super = now_super._super end return false end function class(super, tag) -- 生成一个类类型 local class_type = {} -- 在创建对象的时候自动调用 class_type._tag = tag class_type._ctor = false class_type._delete = false class_type._ctype = ClassType.class local filepath = debug.getinfo(2, "S").short_src class_type._className = filepath:match("^.+/(.+)%.lua?$") class_type._packageName = filepath:match("(.*[/\\])"):match("(.*)/") class_type._super = super class_type.new = function(...) -- 生成一个类对象 local obj = {} obj._class_type = class_type obj._ctype = ClassType.instance obj._super = super obj._className = class_type._className -- 在初始化之前注册基类方法 setmetatable(obj, { __index = _class[class_type], }) -- 调用初始化方法 do local create create = function(c, ...) if c._super then create(c._super, ...) end if _class[c] == nil then print('create: ', table.dump(c)) end local ccc = rawget(_class[c], 'ctor') --print('###### raw get', c._className, ccc) --print('###### c.ctor', c.ctor) if ccc then ccc(obj, ...) end end create(class_type, ...) end -- 注册一个delete方法 obj.delete = function(self) local now_super = self._class_type while now_super ~= nil do if now_super.delete then now_super.delete(self) end now_super = now_super._super end end return obj end local vtbl = {} assert(_class[class_type] == nil, "Already defined class") _class[class_type] = vtbl setmetatable(class_type, { __newindex = function(t,k,v) vtbl[k] = v end , --For call parent method __index = vtbl, }) if super then setmetatable(vtbl, { __index = function(t,k) local ret = _class[super][k] --do not do accept, make hot update work right! --vtbl[k] = ret return ret end }) end return class_type end
LuaClass
最新推荐文章于 2022-04-26 10:34:08 发布