c - 如何应用lua定义

标签 c lua lua-api

我有一个定义如下:

#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就出现错误

最佳答案

首先,您发布了很多与问题完全无关的内容。我们不需要查看 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"); 

问题是找不到您的文件。每the manual , luaL_dofile 返回 true 如果有错误,如果没有错误则返回 false

如果找到该文件,您的程序将中止。只有当文件没有时,它才会尝试索引tbl,但它不能,因为那个全局变量不存在。

关于c - 如何应用lua定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33535299/

相关文章:

c - C 中的信号和回调?

emacs - Lua 支持在 emacs 中自动完成

从 Lua 调用 C 库函数

c++ - 将另一个类的 C++ 静态函数绑定(bind)到 Lua

c程序功能困惑

c malloc 结构数组

c - OpenCL 中的 NDRangeKernel 函数中的局部大小错误

Lua:如何将变量变成方程中的数字?

mysql - 根据行检测列的类型

c++ - Lua C API : inserting table elements cause Debug Assertion Failed