Print stacktrace from C code with embedded lua

Matt Hook picture Matt Hook · Sep 4, 2012 · Viewed 12.5k times · Source

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

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.

i.e.

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

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

Answer

Nicol Bolas picture Nicol Bolas · Sep 4, 2012

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

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.

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