从带有嵌入式 lua 的 C 代码打印堆栈跟踪

编程入门 行业动态 更新时间:2024-10-28 04:28:02
本文介绍了从带有嵌入式 lua 的 C 代码打印堆栈跟踪的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我理解正确的话,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
", 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's 误差函数.调用错误函数时堆栈尚未展开,因此您可以在那里获得堆栈跟踪.运行时使用的错误函数是这个:

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 代码打印堆栈跟踪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-03-29 03:49:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/747844.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:堆栈   嵌入式   代码   lua

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!