lua中基类和“继承机制”

时间:2023-03-08 22:32:37
lua中基类和“继承机制”

基类:基类定义了所有对于派生类来说普通的属性和方法,派生类从基类继承所需的属性和方法,且在派生类中增加新的属性和方法。

继承:继承是C++语言的一种重要机制,它允许在已定义的类的基础上产生新类。

lua基类和C++基类极为相似,但是lua中却没有继承这一说,更没有所谓的派生类。lua只能通过一种行为(元表)来模拟C++继承这一方法。

元表:lua中提供的元表是用于帮助lua数据变量完成某些非预定义功能的个性化行为,当它做某一种操作,然而self表中却没有定义实现这种操作的方法,那么为了实现这一操作便会去元表中找实现这一操作的方法。

如果每一层的元表都定义一种方法指向上一层要“继承”的lua表,这样是不是就和C++继承一样了,有木有!

元方法:C++中的继承不会改变语言的常规行为。但是lua中却提供了一种可以改变table行为的方法,有两种可以改变的table行为:(__index元方法)查询table及( __newindex元方法)修改table中不存在的字段

(1)__index元方法:当对元表中不存在的字段进行访问时,得到的结果为nil。通过定义这个元表的__index,那个访问结果将由这个方法决定。

这个方法也是“继承”父类的方法。

(2)__newindex元方法:当对元表中不存在的字段进行赋值时,解释器会先找到这个元表的__newindex,如果有就调用它,对__newindex指向的表进行赋值操作, 如果没有才对self表进行赋值。

 --保存类类型的虚表
local _class = {} GLOBAL_OBJ_COUNT = {}
ENABLE_OBJ_COUNT = function FindClassName(target, depth)
for key,value in pairs(_G) do
if value == target then
return key
end
end
end function ClasCountRetain(c)
local key = FindClassName(c)
if GLOBAL_OBJ_COUNT[key] == nil then
GLOBAL_OBJ_COUNT[key] =
else
GLOBAL_OBJ_COUNT[key] = GLOBAL_OBJ_COUNT[key] +
end
end function ClasCountRelease(c)
local key = FindClassName(c)
if GLOBAL_OBJ_COUNT[key] == nil then
GLOBAL_OBJ_COUNT[key] = ---标识异常
else
GLOBAL_OBJ_COUNT[key] = GLOBAL_OBJ_COUNT[key] -
end
end function PrintLuaClassCount( ... )
print("PrintLuaClassCount.............")
for key,value in pairs(GLOBAL_OBJ_COUNT) do
print("PrintLuaClassCount:"..key..":",value)
end
end function BaseClass(super) -- 生成一个类类型
local class_type = {}
-- 在创建对象的时候自动调用
class_type.__init = false
class_type.__delete = false
class_type.super = super class_type.New = function(...) --定义New成员方法
-- 生成一个类对象
local obj = {}
obj._class_type = class_type -- 在初始化之前注册基类方法
setmetatable(obj, { __index = _class[class_type] }) -- 调用初始化方法
do
local create
create = function(c, ...)
if c.super then
create(c.super, ...) --对所有基类都进行init
end
if ENABLE_OBJ_COUNT ~= then
ClasCountRetain(c)
end
if c.__init then
c.__init(obj, ...)
end
end create(class_type, ...)
end -- 注册一个delete方法
obj.DeleteMe = function(self)
local now_super = self._class_type
while now_super ~= nil do
if ENABLE_OBJ_COUNT ~= then
ClasCountRelease(now_super)
end
if now_super.__delete then
now_super.__delete(self) --对所有基类都进行delete
end
now_super = now_super.super
end
end return obj
end local vtbl = {}
_class[class_type] = vtbl setmetatable(class_type, {__newindex =
function(t,k,v)
vtbl[k] = v --赋值操作时self找不到的字段则对vtbl表赋值
end
,
__index = vtbl, --For call parent method
}) if super then
setmetatable(vtbl, {__index = --元表做“继承”操作
function(t,k)
local ret = _class[super][k]
return ret
end
})
end return class_type
end