Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to nest modules into namespaces when registering functions from C in Lua?

Tags:

c

lua

I'm trying to "nest" two modules registered from C. I'm trying to separate the concerns a bit.

Here's my "Core" module. It has a single method called "setName"

int l_setName(lua_State *l)
{
    // do something
    return 0;
}

///////////////////////////////////////////////////////////////////////////////

static luaL_Reg const core_funcs [] =
{
    { "setName",            l_setName },
    { NULL, NULL }
};

///////////////////////////////////////////////////////////////////////////////

void l_registerFuncs( lua_State * L )
{
    luaL_newlib(L, core_funcs);
    lua_setglobal(L, "Core");
}

///////////////////////////////////////////////////////////////////////////////

From Lua, you can say Core.setName("hello world")

Here is a complicated subsystem with 20 functions that all have do with the same domain.

int l_importantFunction(lua_State *l)
{
    // do something
    return 0;
}

///////////////////////////////////////////////////////////////////////////////

static luaL_Reg const subSystem_funcs [] =
{
    { "importantFunction",          l_importantFunction },
    { NULL, NULL }
};

///////////////////////////////////////////////////////////////////////////////

void l_registerFuncs( lua_State * L )
{
    luaL_newlib(L, subSystem_funcs);
    lua_setglobal(L, "Core.Subsystem");
}

///////////////////////////////////////////////////////////////////////////////

I want this subsystem to be registered under Core. I want to be able to say Core.Subsystem.importantFunction("Hi")

This won't work however.

What is the idiomatic lua way to do this?

After looking around at how people register "objects", it seems that this could get very complicated.

like image 369
101010 Avatar asked Jan 30 '26 03:01

101010


1 Answers

You need to manually fetch the Core table and then use lua_setfield (or similar) to create the Subsystem entry in that table.

As followed by 010110110101 the above directions became:

lua_getglobal(L, "Core");
luaL_newlib(L, subSystem_funcs);
lua_setfield(L, -2, "SubSystem");
like image 92
Etan Reisner Avatar answered Feb 01 '26 15:02

Etan Reisner