function i3k_clone(obj)
local lookup_table = { };
local function _copy(obj)
if type(obj) ~= "table" then
return obj;
elseif lookup_table[obj] then
return lookup_table[obj];
end
local new_table = { };
lookup_table[obj] = new_table;
for k, v in pairs(obj) do
new_table[_copy(k)] = _copy(v);
end
return setmetatable(new_table, getmetatable(obj));
end
return _copy(obj);
end
function i3k_class(name, super)
local cls = nil;
local stype = type(super);
--如果提供的super既不是函数,也不是table,那么就直接将super当做不存在
if stype ~= "function" and stype ~= "table" then
stype = nil;
super = nil;
end
--如果有提供super
if super and (super.__ctype == nil or super.__ctype == 1) then -- c++ native class
cls = { };-- 定义一个table,它将作为类的定义
--如果super是table,那么将super中定义的字段先全部拷贝到cls中
--然后将__create方法指定为super的__create方法
if super.__ctype then
for k, v in pairs(super) do cls[k] = v; end
cls.__create= super.__create;
else
--这里提供的super时函数,那么也就是用这个方法来构造对象,那么直接将__create方法指向super
cls.__create= function(...) return super:create(...) end;
end
cls.__cname = name;
cls.__ctype = 1;
cls.__super = super;
function cls.getName() return cls.__cname; end
function cls.getSuper() return cls.__super; end
function cls.ctor(...) end--提供一个空的ctor构造函数
--定义.new(...)方法,他用户构建对象,首先是调用__create方法来构建一个table对象,然后将cls里面定义的字段全部拷贝到创建的对象中
--接下来在调用ctor构造方法
function cls.new(...)
local inst = cls.__create(...);
inst.__class = cls;
for k, v in pairs(cls) do inst[k] = v; end
--两个都存在
if cls.__super and cls.__super.ctor then cls.__super.ctor(inst, ...); end
inst.ctor(inst, ...);
return inst;
end
else --从lua的类型中继承
if super then
cls = i3k_clone(super);
cls.__super = super;
else
--直接就没有super,那么定义cls为一个带有空ctor的table
cls = { ctor = function() end };
end
cls.__cname = name;
cls.__ctype = 2; -- lua
cls.__index = cls;
function cls.getName() return cls.__cname; end
function cls.getSuper() return cls.__super; end
--这里的new方法,首先是创建了空的table,然后将其metatable指向为cls
--然后在调用ctor构造方法
function cls.new(...)
local inst = setmetatable({ }, cls);
inst.__class = cls;
local bases = { };
local __super = cls.__super;
while __super ~= nil do
table.insert(bases, __super);
__super = __super.__super;
end
for k = #bases, 1, -1 do
local __super = bases[k];
if __super.ctor then __super.ctor(inst, ...); end
end
inst:ctor(...);
--返回类型的定义
return inst;
end
end
return cls;
end
Person=i3k_class("Person")
function Person:ctor()
self.name="y"
self.age=20
end
p=Person:new()
print(p.name)
print(p.age)
Man=i3k_class("Man",Person)
function Man:ctor()
self.name="yyy"
self.score=100
end
m=Man:new()
print(m.name) -- y 20
print(m.score)-- yyy 100