Friday, March 15, 2013

Lua stack dump for c++


Any interactions between c++ and lua are going through lua stack. Aware of the stack status may help for debugging. I always do that, will a peek of the current Lua stack not only helps me debug my codes but also helps me figure out the ways how I can pass table from c++ to Lua and vice versa.
01void stackdump_g(lua_State* l)
02{
03    int i;
04    int top = lua_gettop(l);
05 
06    printf("total in stack %d/n",top);
07 
08    for (i = 1; i <= top; i++)
09    {  /* repeat for each level */
10        int t = lua_type(l, i);
11        switch (t) {
12            case LUA_TSTRING:  /* strings */
13                printf("string: '%s'/n", lua_tostring(l, i));
14                break;
15            case LUA_TBOOLEAN:  /* booleans */
16                printf("boolean %s/n",lua_toboolean(l, i) ? "true" :"false");
17                break;
18            case LUA_TNUMBER:  /* numbers */
19                printf("number: %g/n", lua_tonumber(l, i));
20                break;
21            default:  /* other values */
22                printf("%s/n", lua_typename(l, t));
23                break;
24        }
25        printf("  ");  /* put a separator */
26    }
27    printf("/n");  /* end the listing */
28}
I usually interested on knowing how many blocks in my stack had been occupied and also each block’s variable type, if they are string, number or bool, I would like to know the value as well.
The usage is simple, you will only needs to pass in your current Lua State pointer.
The print line output may look like this:

total in stack 2
string: '5A5B5C8855778899'
  number: 89

No comments: