Guest User

Untitled

a guest
May 7th, 2012
707
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 10.25 KB | None | 0 0
  1. --[[
  2.   class.lua
  3.   version: 2.05
  4.   2011-11-05
  5.   update by Kernell
  6. ]]
  7.  
  8. --[[
  9.   class.lua
  10.   version: 2.04
  11.   2009-05-20
  12.   update by Setuper
  13. ]]
  14.  
  15. -- PRIVATE
  16.  
  17. --[[
  18.   Define unique value for identifying ambiguous base objects and inherited
  19.   attributes. Ambiguous values are normally removed from classes and objects,
  20.   but if keep_ambiguous == true they are left there and the ambiguous value
  21.   is made to behave in a way useful for debugging.
  22. ]]
  23.  
  24. local ambiguous = { __type = 'ambiguous' };
  25. local remove_ambiguous;
  26.  
  27. if keep_ambiguous then
  28.     -- Make ambiguous complain about everything except tostring()
  29.     local function invalid( operation )
  30.         return function()
  31.             error( 'Invalid ' .. operation .. ' on ambiguous' );
  32.         end
  33.     end
  34.    
  35.     local ambiguous_mt =
  36.     {
  37.         __add       = invalid( 'addition' ),
  38.         __sub       = invalid( 'substraction' ),
  39.         __mul       = invalid( 'multiplication' ),
  40.         __div       = invalid( 'division' ),
  41.         __mod       = invalid( 'modulus operation' ),
  42.         __pow       = invalid( 'exponentiation' ),
  43.         __unm       = invalid( 'unary minus' ),
  44.         __concat    = invalid( 'concatenation' ),
  45.         __len       = invalid( 'length operation' ),
  46.         __eq        = invalid( 'equality comparison' ),
  47.         __lt        = invalid( 'less than' ),
  48.         __le        = invalid( 'less or equal' ),
  49.         __index     = invalid( 'indexing' ),
  50.         __newindex  = invalid( 'new indexing' ),
  51.         __call      = invalid( 'call' ),
  52.         __tostring  = function() return 'ambiguous' end,
  53.         __tonumber  = invalid( 'conversion to number' )
  54.     };
  55.    
  56.     setmetatable( ambiguous, ambiguous_mt );
  57.  
  58.     -- Don't remove ambiguous values from classes and objects
  59.     remove_ambiguous = function() end;
  60. else
  61.     -- Remove ambiguous values from classes and objects
  62.     remove_ambiguous = function( t )
  63.         for k, v in pairs( t ) do
  64.             if v == ambiguous then
  65.                 t[ k ] = nil;
  66.             end
  67.         end
  68.     end
  69. end
  70.  
  71.  
  72. --[[
  73.   Reserved attribute names.
  74. ]]
  75.  
  76. local reserved      =
  77. {
  78.     __index         = true;
  79.     __newindex      = true;
  80.     __type          = true;
  81.     __class         = true;
  82.     __bases         = true;
  83.     __inherited     = true;
  84.     __from          = true;
  85.     __virtual       = true;
  86.     __user_init     = true;
  87.     __name          = true;
  88.     __initialized   = true;
  89. }
  90.  
  91. --[[
  92.   Some special user-set attributes are renamed.
  93. ]]
  94.  
  95. local rename =
  96. {
  97.     __init  = '__user_init';
  98.     __set   = '__user_set';
  99.     __get   = '__user_get';
  100. };
  101.  
  102. --[[
  103.   The metatable of all classes, containing:
  104.  
  105.   To be used by the classes:
  106.    __call()    for creating instances
  107.    __init()     default constructor
  108.    is_a()      for checking object and class types
  109.   implements()  for checking interface support
  110.  
  111.   For internal use:
  112.   __newindex()  for controlling class population
  113. ]]
  114.  
  115. local class_mt = {};
  116. class_mt.__index = class_mt;
  117.  
  118. --[[
  119.   This controls class population.
  120.   Here 'self' is a class being populated by inheritance or by the user.
  121. ]]
  122.  
  123. function class_mt:__newindex( name, value )
  124.     if rename[ name ]       then name = rename[ name ] end -- Rename special user-set attributes
  125.  
  126.     if name == '__user_get' then -- __user_get() needs an __index() handler
  127.         self.__index = value and function( obj, k )
  128.             local v = self[ k ];
  129.            
  130.             if v == nil and not reserved[ k ] then
  131.                 v = value( obj, k );
  132.             end
  133.            
  134.             return v;
  135.         end or self;
  136.     elseif name == '__user_set' then -- __user_set() needs a __newindex() handler
  137.         self.__newindex = value and function( obj, k, v )
  138.             if reserved[ k ] or not value( obj, k, v ) then
  139.                 rawset( obj, k, v );
  140.             end
  141.         end or nil;
  142.     end
  143.    
  144.     rawset( self, name, value ); -- Assign the attribute
  145. end
  146.  
  147. --[[
  148.   This function creates an object of a certain class and calls itself
  149.   recursively to create one child object for each base class. Base objects
  150.   of unnamed base classes are accessed by using the base class as an index
  151.   into the object, base objects of named base classes are accessed as fields
  152.   of the object with the names of their respective base classes.
  153.   Classes derived in virtual mode will create only a single base object.
  154.   Unambiguous grandchildren are inherited by the parent if they do not
  155.   collide with direct children.
  156. ]]
  157.  
  158. local function build( class, virtual_objs, is_virtual )
  159.     virtual_objs = virtual_objs or {};
  160.  
  161.     if is_virtual and virtual_objs[ class ] then
  162.         return virtual_objs[ class ];
  163.     end
  164.  
  165.     local obj = { __type = 'object' };
  166.     local inherited = {}
  167.  
  168.     for i, base in ipairs( class.__bases ) do
  169.         local child = build( base, virtual_objs, class.__virtual[ base ] );
  170.        
  171.         obj[ base.__name ] = child;
  172.  
  173.         for c, grandchild in pairs( child ) do
  174.             if not inherited[c] then
  175.                 inherited[ c ] = grandchild;
  176.             elseif inherited[ c ] ~= grandchild then
  177.                 inherited[ c ] = ambiguous;
  178.             end
  179.         end
  180.     end
  181.  
  182.     for k, v in pairs( inherited ) do
  183.         if not obj[ k ] then
  184.             obj[ k ] = v;
  185.         end
  186.     end
  187.  
  188.     remove_ambiguous( obj );
  189.  
  190.     setmetatable( obj, class );
  191.  
  192.     if is_virtual then virtual_objs[ class ] = obj end
  193.  
  194.     return obj;
  195. end
  196.  
  197. --[[
  198.   The __call() operator creates an instance of the class and initializes it.
  199. ]]
  200.  
  201. function class_mt:__call( ... )
  202.     local this = build( self );
  203.  
  204.     this:__init( ... );
  205.    
  206.     return this;
  207. end
  208.  
  209. function class_mt:__init( ... )
  210.     if self.__initialized then
  211.         return;
  212.     end
  213.    
  214.     if self[ self.__name ] then
  215.         self[ self.__name ]( self, ... );
  216.     end
  217.    
  218.     for _, base in ipairs( self.__bases ) do
  219.         self[ base.__name ]:__init( ... );
  220.     end
  221.    
  222.     self.__initialized = true;
  223. end
  224.  
  225. --[[
  226.   The implements() method checks that an object or class supports the
  227.   interface of a target class. This means it can be passed as an argument to
  228.   any function that expects the target class. We consider only functions
  229.   and callable objects to be part of the interface of a class.
  230. ]]
  231.  
  232. function class_mt:implements( class )
  233.     local function is_callable( v )
  234.         if v == ambiguous then return false end
  235.         if type( v ) == 'function' then return true end
  236.        
  237.         local mt = getmetatable( v );
  238.        
  239.         return mt and type( mt.__call ) == 'function';
  240.     end
  241.  
  242.     for k, v in pairs( class ) do
  243.         if not reserved[ k ] and is_callable( v ) and not is_callable( self[ k ] ) then
  244.             return false;
  245.         end
  246.     end
  247.  
  248.     return true;
  249. end
  250.  
  251. --[[
  252.   The is_a() method checks the type of an object or class starting from
  253.   its class and following the derivation chain upwards looking for
  254.   the target class. If the target class is found, it checks that its
  255.   interface is supported (this may fail in multiple inheritance because
  256.   of ambiguities).
  257. ]]
  258.  
  259. function class_mt:is_a( class )
  260.     if self.__class == class then return true end
  261.  
  262.     local function find( target, classlist )
  263.         for i, class in ipairs( classlist ) do
  264.             if class == target or find( target, class.__bases ) then
  265.                 return true;
  266.             end
  267.         end
  268.        
  269.         return false;
  270.     end
  271.  
  272.     if not find( class, self.__bases ) then return false end
  273.  
  274.     return self:implements( class );
  275. end
  276.  
  277. -- PUBLIC
  278.  
  279. --[[
  280.   Utility type and interface checking functions
  281. ]]
  282.  
  283. function typeof( value )
  284.     return value and value.__type or type( value );
  285. end
  286.  
  287. function classof( value )
  288.     return value and value.__class;
  289. end
  290.  
  291. function classname( value )
  292.     return value and type( value.__name ) == 'string' and value.__name or nil;
  293. end
  294.  
  295. function implements( value, class )
  296.     return classof( value ) and value:implements( class ) or false
  297. end
  298.  
  299. function is_a( value, class )
  300.     return classof( value ) and value:is_a( class ) or false
  301. end
  302.  
  303. --[[
  304.   Use a table to control class creation and naming.
  305. ]]
  306.  
  307. class = {};
  308. local mt = {};
  309.  
  310. setmetatable( class, mt );
  311.  
  312. function mt:__newindex()
  313.     return nil;
  314. end
  315.  
  316. --[[
  317.   Create a named or unnamed class by calling class([name, ] ...).
  318.   Arguments are an optional string to set the class name and the classes or
  319.   virtual classes to be derived from.
  320. ]]
  321.  
  322. function mt:__call( name )
  323.     _G[ name ] = make_class( self, name );
  324.    
  325.     return function( ... )
  326.         _G[ name ] = make_class( self, name, ... );
  327.     end
  328. end
  329.  
  330. function make_class( this, ... )
  331.     local arg, last = { ... }, {};
  332.     local argn = #arg;
  333.    
  334.     if argn ~= 0 then
  335.         local l = arg[ argn ];
  336.        
  337.         if typeof( l ) == "table" then
  338.             last = l;
  339.             table.remove( arg, argn );
  340.         end
  341.     end
  342.  
  343.     local c =
  344.     {
  345.         __type      = 'class',
  346.         __bases     = {},
  347.         __virtual   = {}
  348.     };
  349.    
  350.     c.__class   = c;
  351.     c.__index   = c;
  352.  
  353.     if type( arg[ 1 ] ) == 'string' then
  354.         c.__name    = arg[ 1 ];
  355.        
  356.         table.remove( arg, 1 );
  357.     else
  358.         c.__name    = tostring( c );
  359.     end
  360.  
  361.     local inherited     = {};
  362.     local from          = {};
  363.  
  364.     for i, base in ipairs( arg ) do
  365.         local basetype = typeof( base );
  366.         local is_virtual = basetype == 'virtual_class';
  367.        
  368.         assert( basetype == 'class' or is_virtual, 'Base ' .. i .. ' is not a class or virtual class' );
  369.        
  370.         if is_virtual then
  371.             base = base.__classl;
  372.         end
  373.  
  374.         assert( c.__virtual[ base ] == nil, 'Base ' .. i .. ' is duplicated' );
  375.  
  376.         c.__bases[ i ]          = base;
  377.         c.__virtual[ base ]     = is_virtual;
  378.  
  379.         for k, v in pairs( base ) do
  380.             if not reserved[ k ] and v ~= ambiguous and inherited[ k ] ~= ambiguous then
  381.                 local new_from;
  382.  
  383.                 local base_inherited = base.__inherited[ k ];
  384.                
  385.                 if base_inherited then
  386.                     if base_inherited ~= v then
  387.                         base.__inherited[ k ]   = nil;
  388.                         base.__from[ k ]        = nil;
  389.  
  390.                     else
  391.                         new_from    = base.__from[ k ];
  392.                     end
  393.                 end
  394.  
  395.                 new_from = new_from or { class = base, virtual = is_virtual };
  396.  
  397.                 local current_from = from[ k ];
  398.                
  399.                 if not current_from then
  400.                     from[ k ] = new_from;
  401.  
  402.                     if type( v ) == 'function' then
  403.                         local origin = new_from.class;
  404.                        
  405.                         inherited[ k ] = function( this, ... )
  406.                             return origin[ k ]( this[ origin.__name ], ... );
  407.                         end
  408.  
  409.                     else
  410.                         inherited[ k ] = v;
  411.                     end
  412.                    
  413.                 elseif current_from.class ~= new_from.class or not current_from.virtual or not new_from.virtual then
  414.                     inherited[ k ] = ambiguous;
  415.                     from[ k ] = nil;
  416.                 end
  417.             end
  418.         end
  419.     end
  420.  
  421.     remove_ambiguous( inherited );
  422.  
  423.     setmetatable( c, class_mt );
  424.  
  425.     for k, v in pairs( inherited ) do c[ k ] = v end
  426.    
  427.     c.__inherited = inherited;
  428.     c.__from = from;
  429.  
  430.     for k, v in pairs( last ) do c[ k ] = v end
  431.  
  432.     return c;
  433. end
  434.  
  435. function mt:__index( name )
  436.     return function( ... )
  437.         local c = class( name )( ... );
  438.        
  439.         _G[ name ] = c;
  440.        
  441.         return c;
  442.     end
  443. end
  444.  
  445. --[[
  446.   Wrap a class for virtualization of the class.
  447. ]]
  448.  
  449. function virtual( class )
  450.     assert( typeof( class ) == 'class', 'Argument is not a class' );
  451.    
  452.     return { __type = 'virtual_class', __class = class };
  453. end
Advertisement
Add Comment
Please, Sign In to add comment