【问题标题】:Insert function inside subtable using Lua C API使用 Lua C API 在子表中插入函数
【发布时间】:2016-08-04 23:02:34
【问题描述】:

我正在使用 Lua C API 制作自己的游戏引擎。我得到了这样的 Lua 表层次结构:

my_lib = {
  system = { ... },
  keyboard = { ... },
  graphics = { ... },
  ...
}

我还有一些 C 函数,我想注册,类似这样的:

inline static int lua_mylib_do_cool_things(lua_State *L) {
    mylib_do_cool_things(luaL_checknumber(L, 1));
    return 0;
}

那么,我怎样才能像 my_lib 子表的成员一样注册呢?

my_lib = {
  system = { do_cool_things, ... },
  keyboard = { ... }
  graphics = { ...}
}

现在我只知道注册全局表成员的方法,它是这样工作的:

inline void mylib_registerFuncAsTMem(const char *table, lua_CFunction func, const char *index) {
    lua_getglobal(mylib_luaState, table);
    lua_pushstring(mylib_luaState, index);
    lua_pushcfunction(mylib_luaState, func);
    lua_rawset(mylib_luaState, -3);
}

但是子表呢?

【问题讨论】:

  • API functions可以帮助将函数注册到表中,您使用的是哪个版本的Lua?
  • 感谢您的回复。我用的是Lua 5.1,貌似没有这样的API函数。
  • 没错,这个功能是在 Lua 5.2 中添加的,但你也许可以改用luaL_register
  • @VasiliyPupkin 当然有
  • 您能写一些示例代码吗?正如我所说,我知道如何使用全局表,但不知道子表。

标签: c lua lua-api


【解决方案1】:

将多个 Lua C 函数注册到表中的一种简单方法(使用 Lua 5.1)是使用 luaL_register

首先,实现你的 Lua 函数,它们应该采用lua_CFunction 的形式。

static int graphics_draw(lua_State *L) {
    return luaL_error(L, "graphics.draw unimplemented");
}

static int system_wait(lua_State *L) {
    return luaL_error(L, "system.wait unimplemented");
}

接下来,使用您的 Lua 函数及其名称(键)为每个子表创建一个 luaL_Reg 结构。

static const struct luaL_Reg module_graphics[] = {
    {"draw", graphics_draw},        
    // add more graphic functions here.. 
    {NULL, NULL}  // terminate the list with sentinel value
};

static const struct luaL_Reg module_system[] = {
    {"wait", system_wait},        
    {NULL, NULL}
};

然后,在返回模块表的函数中创建每个子表和register 其函数。

int luaopen_game(lua_State *L) {    
    lua_newtable(L);  // create the module table

    lua_newtable(L);                          // create the graphics table
    luaL_register(L, NULL, module_graphics);  // register functions into graphics table
    lua_setfield(L, -2, "graphics");          // add graphics table to module

    lua_newtable(L);                          // create the system table
    luaL_register(L, NULL, module_system);    // register functions into system table
    lua_setfield(L, -2, "system");            // add system table to module

    // repeat the same process for other sub-tables

    return 1;  // return module table
}

这将产生一个具有以下结构的模块表:

game = {
    graphics = {
        draw -- C function graphics_draw
    },
    system = {
        wait -- C function system_wait
    }
}

【讨论】:

  • 非常感谢。在我提出问题后,我自己找到了解决方案,但您的解决方案要复杂得多。
  • 不客气。这种模式通常用于用 C 编写的 Lua 模块,如优秀的 Programming in Lua 书中所示。第一版可免费在线获取。
猜你喜欢
  • 2011-05-30
  • 2016-11-20
  • 2011-03-20
  • 2011-02-12
  • 2015-05-31
  • 2010-11-27
  • 1970-01-01
  • 2020-06-18
  • 2011-02-17
相关资源
最近更新 更多