lua-users home
lua-l archive

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


It would be easier to answer with a better whole image of your system. How do you create structure? How is the get implemented?

structB.anotherStruct.a
-- is equivalent to
structB["anotherStruct"]["a"]
-- or
local tmpA = structB["anotherStruct"]
tmpA["a"] -- tmpA should be a reference to structA

So you just have to make sure the get method for structB returns a reference to structA. As said above the exact way to do this highly depend on the way you create both structs and how getters are implemented.

In your example you don't seem to create any userdata or table, you just access to the module tables themselves. So I don't understand why you would use structB.anotherStruct instead of directly structA, since both structA and structB are singletons.


-----Message d'origine-----
De : lua-bounces@bazar2.conectiva.com.br [mailto:lua-bounces@bazar2.conectiva.com.br] De la part de Matthias Isele
Envoyé : 25 octobre 2006 12:18
À : Lua list
Objet : Accessing structures in structures

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