简体   繁体   中英

How to nest modules into namespaces when registering functions from C in 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 .

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM