lua-users home
lua-l archive

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


On Thu, Jun 09, 2005 at 09:55:48AM +1200, Russell Y.Webb wrote:

> We need a way to visualize the stack for debugging.
> 
> Is there a console based PrintStack(vm) that someone is willing to put 
> on the Wiki?  I'll write one if no one has it already.

This is my homegrown version.

char* value_description( lua_State* L,
			 int j,
			 char* buf,
			 int size )
{
  int typ,len;
  char* ret;
  const char* value;

  // make a copy to tostring/tonumber functions don't change the
  // original value
  lua_pushvalue( L, j );
  typ = lua_type( L, -1 );
  ret = NULL;

  switch(typ)
    {
    case LUA_TSTRING:
    case LUA_TNUMBER:
      value = lua_tostring(L,-1);
      len = lua_strlen(L,-1);
      copy_with_ellipsis(buf,value,size,len);
      break;
    case LUA_TBOOLEAN:
      value = lua_toboolean(L, -1) ? "TRUE" : "FALSE";
      len = strlen(value) + 1;
      strncpy( buf, value, size );
      buf[size-1] = '\0';  // NULL-terminate, just in case
      break;
    case LUA_TUSERDATA:
    case LUA_TLIGHTUSERDATA:
      snprintf( buf, size, "%p", lua_touserdata(L,-1) );
      buf[size-1] = '\0';
      break;
    case LUA_TTHREAD:
    case LUA_TTABLE:
    case LUA_TFUNCTION:
      snprintf( buf, size, "%p", lua_topointer(L,-1) );
      buf[size-1] = '\0';
      break;
    default:
      value = "???";
      strncpy( buf,value, strlen(value));
      buf[size-1] = '\0';
      break;
    }

  lua_pop(L, 1);
  return buf;
}

#define WRSTK_BUFSIZE 256
int writestack(FILE* f, lua_State* L)
{
  char buf[WRSTK_BUFSIZE];
  int ntop,typ,j;

  ntop = lua_gettop( L );

  for(j = 1; j <= ntop; ++j)
    {
      typ = lua_type( L, j );
      fprintf(f, "[%d]: %s  val: %s\n"
	      , j
	      , lua_typename(L,typ)
	      , value_description(L,j,buf,WRSTK_BUFSIZE) );
    }
  fprintf(f,"\n");

  return 0;
}
#undef WRSTK_BUFSIZE

int dumpstack(lua_State* state)
{
  return writestack(stderr,state);
}

Cheers!

-- 
Shannon Stewman         | Let us walk through the waning night,
Caught in a whirlpool,  | As dawn-rays tickle our toes, the dew soothes
A quartering act:       | Our blistered soles, and damp bones stir
Solitude or society?    | As crimson cracks under the blue-grey sky.