How to register a C function in Lua, but not in a global context, but as a table field?
Register C function in Lua table
11.6k Views Asked by topright gamedev AtThere are 2 best solutions below

This is what luaL_register()
is intended to do, for one or more functions. The canonical usage is as part of the setup for a module written in C:
/* actual definitions of modA() and modB() are left as an exercise. */
/* list of functions in the module */
static const luaL_reg modfuncs[] =
{
{ "a", modA},
{ "b", modB},
{ NULL, NULL }
};
/* module loader function called eventually by require"mod" */
int luaopen_mod(lua_State *L) {
luaL_register(L, "mod", modfuncs);
return 1;
}
where this creates a module named "mod" that has two functions named mod.a
and mod.b
.
Quoting the manual for luaL_register(L,libname,l)
:
When called with
libname
equal toNULL
, it simply registers all functions in the listl
(seeluaL_Reg
) into the table on the top of the stack.When called with a non-null
libname
,luaL_register
creates a new tablet
, sets it as the value of the global variablelibname
, sets it as the value ofpackage.loaded[libname]
, and registers on it all functions in the listl
. If there is a table inpackage.loaded[libname]
or in variablelibname
, reuses this table instead of creating a new one.In any case the function leaves the table on the top of the stack.
luaL_register()
can be used to put C functions in any table by passing NULL
for its second parameter as long as the table is on the top of the stack.