cocos luaはclass解釈を実現する

2294 ワード

function class(classname, ...) --   :       ,   :    ,   function,    table,userdata 
     local cls = {__cname = classname}
 
     local supers = {...}
     for _, super in ipairs(supers) do --      
         local superType = type(super)
         if superType == "function" then
         --    function,    cls create     
             cls.__create = super
         elseif superType == "table" then --    table
             if super[".isclass"] then--      cocos ,  cc.Sprite,      
                 cls.__create = function() return super:create() end
             else
                 --      lua ,       ,  a={}
                 cls.__supers = cls.__supers or {}
                 cls.__supers[#cls.__supers + 1] = super--    __supers    
                 if not cls.super then
                     --         table  cls   
                     cls.super = super
                 end
             end    
         end
     end
 
     cls.__index = cls--     
     if not cls.__supers or #cls.__supers == 1 then --       ,  cls    index        
         setmetatable(cls, {__index = cls.super})
     else
         setmetatable(cls, {__index = function(_, key)--      ,index      ,              
             local supers = cls.__supers
             for i = 1, #supers do
                 local super = supers[i]
                 if super[key] then return super[key] end
             end
         end})
     end
 
     if not cls.ctor then
         --           
         cls.ctor = function() end
     end
     cls.new = function(...) --    ,           
         local instance
         if cls.__create then 
             --   create  ,     ,     ,    cls   create   。
             --           index,      cocos ,  sprite,    sprite:create()
             --        ,      ,      
             
             instance = cls.__create(...)
         else
             instance = {}--  ,       cocos ,     
         end
         --         ,  instance   index,   new ,      instance   index
         --       
         _setmetatableindex(instance, cls)
         instance.class = cls
         instance:ctor(...)--      
         return instance
     end
     cls.create = function(_, ...)
         return cls.new(...)
     end
 
     return cls
end