从嵌入的lua的C代码打印stacktrace

如果我明白这一点,Lua认会在发生错误调用调试库“debug.traceback”.

然而,当将Lua嵌入到C代码中时,如下例所示:
Simple Lua API Example

我们只能在堆栈顶部提供错误消息.

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打印堆栈跟踪?

解决方法

Lua by default will call the debug library “debug.traceback” when an error occurs.

不,不会. Lua运行时(lua.exe)将会这样做,但Lua库不会自己做.如果您想要使用Lua错误调用堆栈,则需要生成一个.

Lua运行时通过使用lua_pcall‘s错误功能执行此操作.当调用错误函数时,堆栈没有被解开,所以可以在那里获取堆栈跟踪.运行时使用的错误功能是这样的:

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,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;
}

相关文章

1.github代码实践源代码是lua脚本语言,下载th之后运行thmai...
此文为搬运帖,原帖地址https://www.cnblogs.com/zwywilliam/...
Rime输入法通过定义lua文件,可以实现获取当前时间日期的功能...
localfunctiongenerate_action(params)localscale_action=cc...
2022年1月11日13:57:45 官方:https://opm.openresty.org/官...
在Lua中的table(表),就像c#中的HashMap(哈希表),key和...