Advertisement
snake5

SGScript - OOP revisited

Feb 21st, 2014
274
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2. // ------------------------------------------------------
  3.  
  4. function def_class( iface )
  5. {
  6.     return class( iface.__init(), iface );
  7. }
  8.  
  9. function def_subclass( superclass, iface )
  10. {
  11.     scdata = get_merged( superclass._data, iface.__init() );
  12.     sciface = get_merged( superclass._super, iface );
  13.     sciface.super = superclass;
  14.    
  15.     sciface.superCall = function( fn )
  16.     {
  17.         args = va_get_args();
  18.         args.shift();
  19.         this.super[ fn ].apply( this, args );
  20.     };
  21.    
  22.     return class( scdata, sciface );
  23. }
  24.  
  25. function new_class( def )
  26. {
  27.     args = va_get_args();
  28.     args.shift();
  29.     inst = clone( def );
  30.     inst.__construct.apply( inst, args );
  31.     return inst;
  32. }
  33.  
  34. // ------------------------------------------------------
  35.  
  36. global testClass = def_class
  37. ({
  38.     __init = function()
  39.     {
  40.         return { count = 1 };
  41.     },
  42.     __construct = function( count )
  43.     {
  44.         if( count )
  45.             this.count = count;
  46.     },
  47.     start = function( message )
  48.     {
  49.         this.pushMessage( message );
  50.         this.count++;
  51.     },
  52.     stop = function()
  53.     {
  54.         this.count--;
  55.     },
  56.     pushMessage = function( msg )
  57.     {
  58.         println( "MESSAGE >>>>>>> " $ msg );
  59.     },
  60. });
  61.  
  62.  
  63. global testSubClass = def_subclass( testClass,
  64. {
  65.     __init = function()
  66.     {
  67.         return { messages = [] };
  68.     },
  69.     __construct = function( count )
  70.     {
  71.         println( "constructing a subclass..." );
  72.         this.superCall( "__construct", count );
  73.     },
  74.     pushMessage = function( msg )
  75.     {
  76.         println( "--------- override ---------" );
  77.         this.messages.push( msg );
  78.         this.superCall( "pushMessage", msg );
  79.         println( "---------   end    ---------" );
  80.     },
  81. });
  82.  
  83. //
  84. // TEST
  85. //
  86. A_inst = new_class( testClass, 41 );
  87. B_inst = new_class( testSubClass, 123 );
  88.  
  89. A_inst.start( "test A" );
  90. B_inst.start( "test B" );
  91.  
  92. println( "\ndata A:" );
  93. printvar( A_inst._data );
  94. println( "\ndata B:" );
  95. printvar( B_inst._data );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement