lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Hi everybody,
I've got a lua problem.
There are two c/c++ structs:

typedef struct structA
{
   int a;
   int b;
};

typedef struct structB;
{
   int x;
   int y;
   structA   anotherStruct;
};

I can access any struct element in lua with the following notation:
structA.a = 1
structA.b = 2
and
structB.x = 3
structB.y = 4
Until here everything works fine.

Now the tricky part (and also my question):
how can I access the structB in structA in a notation like:

structB.anotherStruct.a = 5   in lua.


Here's how I implemented the structs:

static const struct luaL_reg structlib [] = {
     {"set", l_setAStruct},
     {"get", l_getAStruct},
.....
     {NULL, NULL}
   };

int luaopen_structA(lua_State *L)
{
   luaL_newmetatable(L, "opc.structA");

luaL_openlib(L, "structA", structlib, 0);
   // metatable is at index -3
   // "structA" is at index -4
   lua_pushstring(L, "__index");
   lua_pushstring(L, "get");
   lua_gettable(L, -3);
   lua_settable(L, -4);

   lua_pushstring(L, "__newindex");
   lua_pushstring(L, "set");
   lua_gettable(L, -3);
   lua_settable(L, -4);

   return 1;
}

static int l_setAStruct(lua_State *L)
{
structA *a = checkStructA(L, 1); const char* key = lua_tostring(L, 2);
   int value = luaL_checkint(L, 3);

   if( key[0] == 'x' && key[1] == 0)
   {
       a->x = value;
   }
   else if( key[0] == 'y' && key[1] == 0)
   {
       a->y = value;
   }
   else
   {
      // error
      ........
   }
   return 0;
}

The code for structB is analog to this.


Thanks in advance.
Matthias



--
___________________________________
Matthias Isele
ascolab GmbH
Am Weichselgarten 7
91058 Erlangen
Germany
Phone +49 9131 691124
Fax +49 9131 691128
matthias.isele@ascolab.com
www.ascolab.com