Search code examples
c++lualua-table

Adding searcher in package.searchers with lua c api?


Issue

I want require in lua to be able to find module in a game assets archive using Physfs. After some searche, i must add a c function to the package.searchers table ? I tried to do so, but sadly i can't manage to. I'm new to lua and embeding lua, so it is definitly not helping.

One thing i don't get is, the package table and all the nested table in there are not global? I tried to add a lua function to the table (so lua side of things) and i get nothing because package is nil.

With something like this:

package.searchers[#package.searchers + 1] = function(name)
    print("searchers as been called.")
end

Edit

For the package library (and the other one), here is how i basically load it :

const luaL_Reg lualibs[] = {
            { LUA_COLIBNAME, luaopen_base },
            { LUA_LOADLIBNAME, luaopen_package },
            { LUA_TABLIBNAME, luaopen_table },
            { LUA_IOLIBNAME, luaopen_io },
            { LUA_OSLIBNAME, luaopen_os },
            { LUA_STRLIBNAME, luaopen_string },
            { LUA_MATHLIBNAME, luaopen_math },
            { LUA_DBLIBNAME, luaopen_debug },
            { NULL, NULL }
        };

lua_State* ls = luaL_newstate();

const luaL_Reg* lib = lualibs;
for (; lib->func; lib++) {
    lua_pushcfunction(ls, lib->func);
    lua_pushstring(ls, lib->name);
    lua_call(ls, 1, 0);
}

Edit 2

Problem solved, thanks to Egor Skriptunoff's answere. All i have to do was loading the libraries with luaL_openlibs directly. then i can do something like that :

lua_getglobal(_ls, LUA_LOADLIBNAME);
if (!lua_istable(_ls, -1))
    return;

lua_getfield(_ls, -1, "searchers");
if (!lua_istable(_ls, -1))
    return;

lua_pushvalue(_ls, -2);
lua_pushcclosure(_ls, mysearcher, 1);
lua_rawseti(_ls, -2, 5);
lua_setfield(_ls, -2, "searchers");

Some info

I use LUA 5.4
It's a c++ project.


Solution

  • I guess i have to post and answere to mark this post as solved.

    First things, package table was not global because i was loading libraries wrong. i need to use luaL_requiref as mentioned by Egor Skriptunoff or directly luaL_openlibs.

    Then after that, because it is now global, i can just do something like that for exemple :

    lua_getglobal(_ls, LUA_LOADLIBNAME);
    if (!lua_istable(_ls, -1))
        return;
    
    lua_getfield(_ls, -1, "searchers");
    if (!lua_istable(_ls, -1))
        return;
    
    lua_pushvalue(_ls, -2);
    lua_pushcclosure(_ls, mysearcher, 1);
    lua_rawseti(_ls, -2, 5);
    lua_setfield(_ls, -2, "searchers");