20

如果我理解正确,Lua 默认会在发生错误时调用调试库“debug.traceback”。

但是,当将 Lua 嵌入到 C 代码中时,就像这里的示例中所做的那样: Simple Lua API Example

我们只有堆栈顶部的错误消息。

IE

if (status) {
    /* If something went wrong, error message is at the top of */
    /* the stack */
    fprintf(stderr, "Couldn't load file: %s\n", lua_tostring(L, -1));

    /* I want to print a stacktrace here. How do I do that? */
    exit(1);
}

初始错误后如何从 C 打印堆栈跟踪?

4

4 回答 4

20

Lua 默认会在发生错误时调用调试库“debug.traceback”。

不,不会的。Lua运行时(lua.exe) 会执行此操作,但 Lua 库不会自行执行此操作。如果你想要一个带有 Lua 错误的调用堆栈,那么你需要生成一个。

Lua 运行时通过使用lua_pcall's error 函数来做到这一点。调用错误函数时堆栈尚未展开,因此您可以在那里获得堆栈跟踪。运行时使用的错误函数是这个:

static int traceback (lua_State *L) {
  if (!lua_isstring(L, 1))  /* 'message' not a string? */
    return 1;  /* keep it intact */
  lua_getfield(L, LUA_GLOBALSINDEX, "debug");
  if (!lua_istable(L, -1)) {
    lua_pop(L, 1);
    return 1;
  }
  lua_getfield(L, -1, "traceback");
  if (!lua_isfunction(L, -1)) {
    lua_pop(L, 2);
    return 1;
  }
  lua_pushvalue(L, 1);  /* pass error message */
  lua_pushinteger(L, 2);  /* skip this function and traceback */
  lua_call(L, 2, 1);  /* call debug.traceback */
  return 1;
}
于 2012-09-04T03:47:15.830 回答
10

在这里解决尼科尔的答案是一个工作示例:

static int traceback(lua_State *L) {
    lua_getfield(L, LUA_GLOBALSINDEX, "debug");
    lua_getfield(L, -1, "traceback");
    lua_pushvalue(L, 1);
    lua_pushinteger(L, 2);
    lua_call(L, 2, 1);
    fprintf(stderr, "%s\n", lua_tostring(L, -1));
    return 1;
}

int main(int argc, char **argv) {
    lua_State *L = lua_open();
    luaL_openlibs(L);    
    lua_pushcfunction(L, traceback);
    int rv = luaL_loadfile(L, "src/main.lua");
    if (rv) {
        fprintf(stderr, "%s\n", lua_tostring(L, -1));
        return rv;
    } else {
        return lua_pcall(L, 0, 0, lua_gettop(L) - 1);
    }
}
于 2013-05-01T17:41:05.580 回答
7

我像你一样遇到了一些问题,我发现这种方式有效:

luaL_traceback(L, L, NULL, 1);
printf("%s\n", lua_tostring(L, -1));

由于luaL_traceback正是debug.traceback()用于打印堆栈,所以我认为这可能是一种正确的方法,您可以阅读 API 手册luaL_traceback或只是阅读 Lua 的源代码以了解参数的含义。

于 2015-09-16T09:10:41.813 回答
2

mxcl的代码有问题:

static int traceback(lua_State *L) {
    lua_getfield(L, LUA_GLOBALSINDEX, "debug");
    lua_getfield(L, -1, "traceback");
    //---------------------------
    lua_pop(L,-2); //to popup the 'debug'
    //---------------------------
    lua_pushvalue(L, 1);
    lua_pushinteger(L, 2);
    lua_call(L, 2, 1);
    fprintf(stderr, "%s\n", lua_tostring(L, -1));
    return 1;
}
于 2014-04-13T18:48:29.953 回答