--首先第一步需要是克隆,是为了能够实现子类拥有父类的所有函数和成员变量
function clone(object)
local lookup_table = {}local function _copy(object)
if type(object) ~= "table" then --只有是table 那么我们才进行一个递归拷贝
return object
elseif lookup_table[object] then --再拷贝的过程当中可能会遇到相同的地址的table。比如原table可能就有重复的索引。
-- 这里全部认为是一个,因为table本来就是传的引用,改一个等于改全部。
end
local new_table = {}
lookup_table[object] = new_table
for key, value in pairs(object) do
new_table[_copy(key)] = _copy(value) --key值也可能是个table,也可能是个函数,这个在lua 语法上面是没有限制的。
end
return setmetatable(new_table, getmetatable(object)) --复制元表。
end
return _copy(object)
end
function class(classname, super)
local superType = type(super)
local cls
--一般情况下 superType 都是function 和table
-- 这里需要注意集成function,这个function只要返回的是一个对象就可以满足条件。
if superType ~= "function" and superType ~= "table" thensuperType = nil
super = nil
end
--这里处理的是直接集成C++类,暂时没有用到这个功能。
if superType == "function" or (super and super.__ctype == 1) then
-- inherited from native C++ Object
cls = {}
if superType == "table" then
-- copy fields from super
for k,v in pairs(super) do cls[k] = v end
cls.__create = super.__create
cls.super = super
else
cls.__create = super
cls.ctor = function() end
end
cls.__cname = classname
cls.__ctype = 1
--这里我们可以看到,在使用一个lua类的时候必定有一个new函数。通过这个函数
--然后创建一个instance,这个实例,所以类的本身并不是他自己,而是这个类里面创建的instance实例。
-- 也可以引出 一个类中函数使用的self其实并不是本身,而是创建这个类的返回的实例。
--比如 object:(aa), object.(self,aa) 不同的含义。 因为第一个传的self是object,而第二个并一定是object。
function cls.new(...)local instance = cls.__create(...)
-- copy fields from class to native object
for k,v in pairs(cls) do instance[k] = v end
instance.class = cls
instance:ctor(...)
return instance
end
else
-- inherited from Lua Object
if super then
cls = {}
setmetatable(cls, {__index = super})
cls.super = super
else
cls = {ctor = function() end}
end
cls.__cname = classname
cls.__ctype = 2 -- lua
cls.__index = cls
function cls.new(...)
local instance = setmetatable({}, cls)
instance.class = cls
instance:ctor(...)
return instance
end
end
return cls
end
--总的来说 ,类的时候第一步 要实现克隆,第二步把父类作为子类的_index的字段。