Skip to content

Commit

Permalink
feat: Extend and clean up a clua debug function
Browse files Browse the repository at this point in the history
For `crawl.stack()`, allow passing a coroutine as an argument, so that
we can examine its stack instead of the current clua one. This is
necessary for debugging something like qw, which wraps its main
execution in a coroutine. I use standard lua functions for checking when
an argument is a lua "thread" (lua's terminology for coroutines) and
converting a coroutine into a lua state. The approach used in this
commit is modeled on what the `debug` library `stacktrace()` function
does to examine coroutines, as seen here:

https://github.com/crawl/crawl-lua/blob/master/src/ldblib.c#L99

I've tested this with qw, and it works as expected.

This commit also removes the request in the call `lua_getinfo()` for the
number of upvalues, since this isn't used. It also fixes up and
completes the lua documentation of `crawl.stack()`.

Resolves crawl#2677.
  • Loading branch information
gammafunk committed Jul 27, 2024
1 parent 3a32abd commit 51ccf8c
Showing 1 changed file with 13 additions and 5 deletions.
18 changes: 13 additions & 5 deletions crawl-ref/source/l-crawl.cc
Original file line number Diff line number Diff line change
Expand Up @@ -141,27 +141,35 @@ LUAFN(crawl_dpr)
return 0;
}

/*** Returns the current lua stack, for debugging.
* @treturn string channel name
/*** Returns a string representation of the stack of either the current clua
* state or that of a coroutine. This is useful for debugging clua code.
* @tparam[opt] coroutine A coroutine to analyze instead of the current clua state.
* @treturn string The stack trace
* @function stack
*/
LUAFN(crawl_stack)
{
lua_State *ls1 = ls;
if (lua_isthread(ls, 1))
ls1 = lua_tothread(ls, 1);

string r;
struct lua_Debug dbg;
int i = 0;
while (lua_getstack(ls, i++, &dbg) == 1)
while (lua_getstack(ls1, i++, &dbg) == 1)
{
lua_getinfo(ls, "lnuS", &dbg);
lua_getinfo(ls1, "lnS", &dbg);
char* file = strrchr(dbg.short_src, '/');
if (file == nullptr)
file = dbg.short_src;
else
file++;
char buf[1000];
snprintf(buf, 1000, "%s, function %s, line %d\n", file, dbg.name, dbg.currentline);
snprintf(buf, 1000, "%s, function %s, line %d\n", file, dbg.name,
dbg.currentline);
r += buf;
}

lua_pushstring(ls, r.c_str());
return 1;
}
Expand Down

0 comments on commit 51ccf8c

Please sign in to comment.