提交 9f5317a3 编写于 作者: Emo_Tiny's avatar Emo_Tiny

lua框架底层提交

上级 29897500
......@@ -26,8 +26,84 @@ local _mtBaseClass =
__tostring = _Tostring
}
--实例化
local function _Instantiate(self, ...)
assert(_IsA(self,"class"),"Class must be called from a class")
assert(not _registry.class[self].__abstract,"Can not Instantiate from an abstract class")
local instance = _DeepCopy[self]
_registry.object[instance] =
{
__type = "object",
__superClass = self,
__addr = tostring(instance)
}
setmetatable(instance, { __index = self,
-- 提供gc时的析构调用,由于gc时机不定,所以不要依赖此方法做资源释放
__gc = function(obj)
if _IsA(obj, "object") and obj.__dtor then
obj:__dtor()
end
end,
__tostring = self.__tostring,
--__newindex = function(t, k, v) logerror(string.format("'%s' is not exist in %s", k, t)) end
})
-- 构造调用
if self.__ctor then
self.__ctor(instance, ...)
end
return instance
end
--用于判断一个数据的类型,一般用于判断一个table是否是class还是object
local function _IsA(thing,kind)
if kind then
assert(kind == "object" or kind == "class","when given,string 'kind' must be a class or an 'object'")
end
if thing then
if _registry.class[thing] then
if kind then
return _registry.class[thing].__type == kind
else
return _registry.class[thing].__type
end
elseif _registry.object[thing] then
return _registery.object[thing].__type == kind
else
return _registery.object[thing].__type
end
end
return false
end
--深拷贝,针对于luaTable,一般也即为类
local function _DeepCopy(t)
local r = {}
for k, v in pairs(t) do
local vtype = type(v)
if vtype == "table" then
if _registry.class[v] or _registry.object[v] then
r[k] = v
else
_DeepCopy(v)
end
elseif(vtype ~= "function") then
r[k] = v
end
end
end
--普通继承
local function _Extends(self,name ,flags)
assert(_IsA(self,"class"),"Inheritance must be called from a class")
assert(not _registry.class[self].__final,"Can not derive from a final class")
local class = _CreateClass(name,flags)
class.__index = class
class.__tostring = _ToString
_registry.class[class].__superClass = self
_registry.class[self].__subClass = class
return setmetatable(class,self)
end
function _CreateClass(name,flags)
......@@ -40,8 +116,8 @@ function _CreateClass(name,flags)
__name = name,
__abstract = flags and flags.abstract or false,
__final = flags and flags.final or false,
__superClass = false,
__subClass = setmetatable({},{__mode = "k"}),
__superClass = false, --父类
__subClass = setmetatable({},{__mode = "k"}), --子类
__addr = tostring(newClass)
}
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册