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