3

In a game that uses Lua for extensibility, when an error is thrown in a script, I'd like to show the user an error log, i.e. an error message and a stack trace, somewhat like this:

if (lua_pcall(L, nargs, nresults, 0) != 0) log.printline(lua_tostring(L, -1));

This only prints the error message, though, not the call stack.

I am aware I could use debug.traceback, i.e. grabbing the function from the debug table through the API and then calling it, but I don't want to load the debug table at all because of security concerns, i.e. allowing a malicious user to write scripts that screw with the system and other global tables. (For the same reason I don't load io and instead expose my own functions.)

I'm not using a bridge of any sort, I use the Lua API directly, through P/Invoke.

How would I go about printing a stack trace following a failed lua_pcall call, without having to expose the debug table to the end user?

BinarySpark
  • 125
  • 9

2 Answers2

3

Call luaL_traceback:

void luaL_traceback (lua_State *L, lua_State *L1, const char *msg, int level);

Creates and pushes a traceback of the stack L1. If msg is not NULL it is appended at the beginning of the traceback. The level parameter tells at which level to start the traceback.

You probably want to use L1=L. See the source of lua.c for an example of use.

Community
  • 1
  • 1
lhf
  • 70,581
  • 9
  • 108
  • 149
  • Looks like luaL_traceback is only available in 5.2 and up. I'm using 5.1, will try and see if I can migrate, was planning to anyway... – BinarySpark Feb 03 '16 at 11:53
  • Works perfectly. Thanks! – BinarySpark Feb 03 '16 at 20:18
  • 1
    `luaL_traceback` have been backported to Lua 5.1: https://github.com/keplerproject/lua-compat-5.2/blob/master/c-api/compat-5.2.c#L226. See also http://stackoverflow.com/questions/12256455/print-stacktrace-from-c-code-with-embedded-lua. – lhf Feb 04 '16 at 10:02
  • I settled for implementing `luaL_traceback` by having it push `db_errorfb` (which is debug.traceback) on the stack, its arguments, and then calling it through lua_call. – BinarySpark Feb 04 '16 at 10:31
0

4th argument in lua_pcall is error handler. So you can call some think like debug.traceback in this function to get stacktrace and do log in this function.

moteus
  • 2,187
  • 1
  • 13
  • 16
  • I can't call `debug.traceback` from a Lua function because of security concerns. That's kind of the entire problem. – BinarySpark Feb 03 '16 at 11:11