Advertisement
snake5

SGScript native objects + meta-objects for methods

Jul 31st, 2014
400
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.52 KB | None | 0 0
  1. int nom_method_A( SGS_CTX )
  2. {
  3.     SGSFN( "nom::method_A" );
  4.     sgs_PushInt( C, 5 );
  5.     if( sgs_Method( C ) )
  6.     {
  7.         sgs_PushItem( C, -1 );
  8.         sgs_StoreProperty( C, 0, "a" );
  9.     }
  10.     return 1;
  11. }
  12.  
  13. int nom_method_B( SGS_CTX )
  14. {
  15.     SGSFN( "nom::method_B" );
  16.     sgs_PushInt( C, 7 );
  17.     if( sgs_Method( C ) )
  18.     {
  19.         sgs_PushItem( C, -1 );
  20.         sgs_StoreProperty( C, 0, "b" );
  21.     }
  22.     return 1;
  23. }
  24.  
  25. int nom_ctor( SGS_CTX )
  26. {
  27.     SGSFN( "nom::nom" );
  28.     sgs_Method( C );
  29.     if( sgs_ItemType( C, 0 ) != SGS_VT_OBJECT )
  30.         return sgs_Msg( C, SGS_WARNING, "metaobj(this) is not an object" );
  31.     sgs_PushDict( C, 0 );
  32.     sgs_ObjSetMetaObj( C, sgs_GetObjectStruct( C, -1 ), sgs_GetObjectStruct( C, 0 ) );
  33.     return 1;
  34. }
  35.  
  36. DEFINE_TEST( native_obj_meta )
  37. {
  38.     SGS_CTX = get_context();
  39.    
  40.     /* create metaobject */
  41.     sgs_PushString( C, "method_A" );
  42.     sgs_PushCFunction( C, nom_method_A );
  43.     sgs_PushString( C, "method_B" );
  44.     sgs_PushCFunction( C, nom_method_B );
  45.     sgs_PushString( C, "__call" );
  46.     sgs_PushCFunction( C, nom_ctor );
  47.     atf_assert( sgs_PushDict( C, 6 ) == SGS_SUCCESS );
  48.     atf_assert( sgs_StackSize( C ) == 1 );
  49.     sgs_ObjSetMetaMethodEnable( sgs_GetObjectStruct( C, -1 ), 1 );
  50.    
  51.     /* register as ctor/iface */
  52.     sgs_StoreGlobal( C, "nom" );
  53.    
  54.     /* try creating and running the object */
  55.     atf_assert( sgs_ExecString( C, ""
  56.         "a = nom();\n"
  57.         "printvar(a.method_A());\n"
  58.         "printvar(a.method_B());\n"
  59.         "function nom.method_C(){ this.c = 9; return 9; }\n"
  60.         "printvar(a.method_C());\n"
  61.         "printvar(a);\n"
  62.     "" ) == SGS_SUCCESS );
  63.    
  64.     destroy_context( C );
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement