使用嵌入式lua从C代码打印stacktrace [英] Print stacktrace from C code with embedded lua

查看:116
本文介绍了使用嵌入式lua从C代码打印stacktrace的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我理解正确,默认情况下,Lua会在发生错误时调用调试库"debug.traceback".

If I understand this correctly, Lua by default will call the debug library "debug.traceback" when an error occurs.

但是,将Lua嵌入到C代码中时(如此处的示例所示): 简单Lua API示例

However, when embedding Lua into C code like done in the example here: Simple Lua API Example

我们仅在堆栈顶部显示错误消息.

We only have available the error message on the top of the stack.

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

How do I print the stack trace from C after the initial error?

推荐答案

默认情况下,Lua在发生错误时将调用调试库"debug.traceback".

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

不,不会. Lua runtime (lua.exe)将执行此操作,但是Lua库不会单独执行此操作.如果您想要一个包含Lua错误的调用栈,则需要生成一个.

No, it won't. The Lua runtime (lua.exe) will do that, but the Lua library will not do that on its own. If you want a call-stack with your Lua errors, then you need to generate one.

Lua运行时通过使用 lua_pcall来做到这一点错误功能.调用错误函数时,尚未取消堆栈的堆栈,因此您可以在那里获取堆栈跟踪.运行时使用的错误函数是此函数:

The Lua runtime does this by using lua_pcall's error function. The stack has not been unwound when the error function is called, so you can get a stack trace there. The error function the runtime uses is this one:

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

这篇关于使用嵌入式lua从C代码打印stacktrace的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆