如何使用Lua的定义

我有以下定义:

#define namef (s, r, x) (p_name ((s), (r), (x)))

我的 lua 文件如下:

tbl= {
    name_func = module;
};

我的代码如下:

void getname(void) {
    lua_State *L = luaL_newstate();
    luaL_openlibs(L);
    char *arc = "luafun.lua";

    if (luaL_dofile(L, arc)) {
        printf("Error in %s", arc);
        return;
    }

    lua_getglobal(L, "tbl");
    lua_getfield(L, -1, "name_func");
    namef(r_name, lua_tostring(L, -1), sizeof(r_name));

    lua_close(L);
    printf("done");
}

r_name 是一个数组 char r_name [11];

但是它给出了以下错误:

PANIC: unprotected error in call to Lua API (attempt to index a nil value)

我不知道为什么会发生这种情况,在 C 中正常工作,但转换为 lua 后出错。

点赞
用户501459
用户501459

首先,你发布了很多与问题完全无关的内容。我们不需要看到 p_name 或者你的宏定义或与 Lua 错误无关的任何内容。参见:volume is not precision。在自行排除此问题时,你应该删除多余的内容,直到只留下最小的代码段出现问题。你最终会得到像这样的代码:

  lua_State *L = luaL_newstate();
  if (luaL_dofile(L, lua_filename)) {
     return;
  }
  lua_getglobal(L, "tbl");
  lua_getfield(L, -1, "name_func");

问题在于你的文件没有被找到。依据手册所述,如果出现错误,luaL_dofile 会返回 true,如果没有错误则返回 false

只有当文件找不到时,程序才会中止。只有当文件 找不到 时,才会尝试索引 tbl,但它不存在,因此无法完成操作。

2015-11-05 05:41:04