--
-- Class helper routines
--
-- Instantiates a class
local function _instantiate(class, ...)
local inst = setmetatable({}, {__index = class})
if inst.__init__ then
inst:__init__(...)
end
return inst
end
--- Create a Class object (Python-style object model).
-- The class object can be instantiated by calling itself.
-- Any class functions or shared parameters can be attached to this object.
-- Attaching a table to the class object makes this table shared between
-- all instances of this class. For object parameters use the __init__ function.
-- Classes can inherit member functions and values from a base class.
-- Class can be instantiated by calling them. All parameters will be passed
-- to the __init__ function of this class - if such a function exists.
-- The __init__ function must be used to set any object parameters that are not shared
-- with other objects of this class. Any return values will be ignored.
-- @param base The base class to inherit from (optional)
-- @return A class object
-- @see instanceof
-- @see clone
function class(base)
-- __parent 属性缓存父类,便于子类索引父类方法
return setmetatable({__parent = base}, {
__call = _instantiate,
__index = base
})
end
--[[
local function searchParentClass(k, plist)
for i=1, #plist do
local v = plist[i][k]
if v then return v end
end
end
--- Create a Class object (Python-style object model).
-- The class object can be instantiated by calling itself.
-- Any class functions or shared parameters can be attached to this object.
-- Attaching a table to the class object makes this table shared between
-- all instances of this class. For object parameters use the __init__ function.
-- Classes can inherit member functions and values from a base class.
-- Class can be instantiated by calling them. All parameters will be passed
-- to the __init__ function of this class - if such a function exists.
-- The __init__ function must be used to set any object parameters that are not shared
-- with other objects of this class. Any return values will be ignored.
-- @param base The base class to inherit from (optional)
-- @return A class object
-- @see instanceof
-- @see clone
function class(...)
local mtb = {}
local parents = {...}
mtb = setmetatable(mtb, {
__call = _instantiate,
__index = function(t,k)
return searchParentClass(k, parents)
end})
mtb.__index = mtb
return mtb
end
]]
--- Test whether the given object is an instance of the given class.
-- @param object Object instance
-- @param class Class object to test against
-- @return Boolean indicating whether the object is an instance
-- @see class
-- @see clone
function instanceof(object, class)
local meta = getmetatable(object)
while meta and meta.__index do
if meta.__index == class then
return true
end
meta = getmetatable(meta.__index)
end
return false
end
请发表评论