lua-users home
lua-l archive

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


2012/12/7 Philipp Kraus <philipp.kraus@flashpixx.de>:
> I'm using lua_register to register some C function. I can call them in my Lua script. I would like to build packages, something like: mypackage.mysubpackage.myfunction
> The functions (functionpointers) read from a DLL, so I know the name of the package, subpackage and the pointer of the function. How can I build the package structure?
> Can I add the packagename to the lua_register eg lua_register(L, "package.subpackage.myfunction", funcptr) ?

You cannot use lua_register to create such packages. What you need to
do is create a table on the stack, add your functions to that table,
and set the table in the globals. For example:

lua_newtable(L);
    lua_pushcfunction(L, myfunction_pointer);
    lua_setfield(L, -2, "myfunction");
    lua_pushcfunction(L, myfunction2_pointer);
    lua_setfield(L, -2, "myfunction2");
lua_setglobal(L, "mypackage");

If you want sub-packages, you can create sub-tables :

lua_newtable(L);
    lua_newtable(L);
        lua_pushcfunction(L, myfunction_pointer);
        lua_setfield(L, -2, "myfunction");
        lua_pushcfunction(L, myfunction2_pointer);
        lua_setfield(L, -2, "myfunction2");
    lua_setfield(L, -2, "mysubpackage");
    lua_newtable(L);
        lua_pushcfunction(L, myfunction3_pointer);
        lua_setfield(L, -2, "myfunction3");
        lua_pushcfunction(L, myfunction4_pointer);
        lua_setfield(L, -2, "myfunction4");
    lua_setfield(L, -2, "mysubpackage2");
lua_setglobal(L, "mypackage");

You can also use helper functions to help you do that, depending on
the Lua version you use that would be luaL_register or luaL_setfuncs.