c++lualua-c++-connection

Register C function in Lua table


How to register a C function in Lua, but not in a global context, but as a table field?


Solution

  • void register_c_function(char const * const tableName, char const * const funcName, CFunctionSignature funcPointer)
    {
        lua_getfield(lstate, LUA_GLOBALSINDEX, tableName);  // push table onto stack
        if (!lua_istable(lstate, -1))                       // not a table, create it
        {
            lua_createtable(lstate, 0, 1);      // create new table
            lua_setfield(lstate, LUA_GLOBALSINDEX, tableName);  // add it to global context
    
            // reset table on stack
            lua_pop(lstate, 1);                 // pop table (nil value) from stack
            lua_getfield(lstate, LUA_GLOBALSINDEX, tableName);  // push table onto stack
        }
    
        lua_pushstring(lstate, funcName);       // push key onto stack
        lua_pushcfunction(lstate, funcPointer); // push value onto stack
        lua_settable(lstate, -3);               // add key-value pair to table
    
        lua_pop(lstate, 1);                     // pop table from stack
    }