lua-users home
lua-l archive

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


On 09/10/2014 04:53 AM, Flávio Alberto wrote:
Hello,
thanks for all help at now !

I try :

<...>
     lua_newtable(L); // create 'mastertable'

     lua_newtable(L); // create 'table1'
     luaL_getmetatable(L, "luasystem.mastertable"); // get metatable
from the registry
     lua_setmetatable(L, -2); // setmetatable(table1, __mt)
     luaL_register(L, NULL, meths);
     lua_setfield(L, -2, "table1");

     lua_newtable(L);
     lua_setfield(L, -2, "table2");

     lua_newtable(L);
     lua_setfield(L, -2, "table3");

     lua_setglobal(L,"mastertable");
<...>

But again l_index and l_newindex was never called...
Really I need to understand the lua stack concepts and how to "link"
these lua objects.


Thanks
Flávio Lopes




you should not call luaL_register this way -- lua_setmetatable would pop the metatable
from the stack.

you can register the metamethods at the creation time of the metatable, once.
then you just retrieve it from the registry when you need it.

the complete code should be:

~~~~

void luaopen_mastertable (lua_State* L)
{
    // create 'mastertable'
    lua_newtable(L);

    // create new table
    lua_newtable(L);

    // set the metatable for newly created table
    // but firstly create the metatable and set the metamethods
    luaL_newmetatable(L, "luasystem.mastertable");
    luaL_register(L, NULL, methods);

    lua_setmetatable(L, -2);

    // mastertable.table1 = <newly created table>
    lua_setfield(L, -2, "table1");

    // mastertable.table2 = {}
    lua_newtable(L);
    lua_setfield(L, -2, "table2");

    // mastertable.table3 = {}
    lua_newtable(L);
    lua_setfield(L, -2, "table3");

    // set the global variable
    lua_setglobal(L,"mastertable");

    // now the stack is balanced as we entered this function.
}

~~~~

note that I intentionally changed the function signature -- this function is not called from
Lua, so it need not be a `lua_CFunction` type. you should not annotate it with LUALIB_API
for the same reason. (besides, a lua_CFunction shoud be called indirectly via lua_call,
lua_pcall/lua_cpcall, in which case you leave the value to be returned to its caller on the
stack and Lua would adjust the stack if needed.)

the Lua C API is actually very intuitive imo. you just need some time to get used to it.
in general, many operations need the RHS operand to be at the top and would pop the value
after the operations. Think in Lua (not in C) and you'll feel comfortable for that.