lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


It was thus said that the Great Dirk Laurie once stated:
> 2015-03-05 3:11 GMT+02:00 Dave Hayden <dave@panic.com>:
> > On Mar 4, 2015, at 5:02 PM, Dave Hayden <dave@panic.com> wrote:
> >
> > Is there some new way of getting a stack trace when lua fails an assert?

  If you mean something like this:
  
  stack= [@/tmp/x.lua(7):]      [=[C](-1):assert]       [@/tmp/x.lua(25):gamma]
	 [@/tmp/x.lua(30):beta] [@/tmp/x.lua(34):alpha] [@/tmp/x.lua(37):]
	 [=[C](-1):xpcall]      [@/tmp/x.lua(37):]      [=[C](-1):]

then:

	syslog = require "org.conman.syslog"

	function stackdump(...)
	  local stack = {}
	  for i = 1 , 10 do
	    local info = debug.getinfo(i,"Sln")
	    if not info then break end
	    table.insert(
	        stack,
	        string.format(
	                " [%s(%d):%s] ",
	                info.source,
	                info.currentline,
	                info.name or "?"
	        ))
	  end
	
	  syslog('debug',"stack=%s",table.concat(stack))
	  return ...
	end
	
	function gamma(x)
	  assert(x == 1)
	  return x + 1
	end

	function beta(x)   
	  return gamma(x)+1
	end
	
	function alpha(x) 
	  return beta(x)+1
	end
	
	okay,err = xpcall(function() print(alpha(3)) end,stackdump)

Or ... 

> Whenever I write in the C API, I cruise along happily without brakes
> until I get my first segmentation error.
> 
> Then I include the following code (5.2) in my program:
> 
> static void stackprint(lua_State *L, int from) {
>    int top=lua_gettop(L);
>    printf("Stack:");
>    while (from<=top)
>       printf(" %i",luaL_checkint(L,from++));
>    printf("\n");
> }
> 
> and sprinkle calls to it liberally in the region of the failed assert.
> It needs to be modified for 5.3 (no luaL_checkint) anyway, so
> one might as well change the print line to print other things than
> integers.

  Here's the function I use to dump the Lua stack:

static void dumpstack(lua_State *L)
{
  int max;
  int i;
  
  max = lua_gettop(L);
  for (i = 1 ; i <= max ; i++)
  {
    const char *value;
    const char *type;
    int         ri;
    
    lua_getglobal(L,"tostring");
    lua_pushvalue(L,i);
    lua_call(L,1,1);
    
    value = lua_tostring(L,-1);
    type  = luaL_typename(L,i);
    ri    = i - max - 1;
    
    /* select your favorite way to display this */
    fprintf(stderr,"Stack: %d %d - %s %s",i,ri,type,value);
    lua_pop(L,1);
  }
}

  -spc