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.

void stackdump_g(lua_State* l)
    int i;
    int top = lua_gettop(l);

    printf("total in stack %d\n",top);

    for (i = 1; i <= top; i++)
    {  /* repeat for each level */
        int t = lua_type(l, i);
        switch (t) {
            case LUA_TSTRING:  /* strings */
                printf("string: '%s'\n", lua_tostring(l, i));
            case LUA_TBOOLEAN:  /* booleans */
                printf("boolean %s\n",lua_toboolean(l, i) ? "true" : "false");
            case LUA_TNUMBER:  /* numbers */
                printf("number: %g\n", lua_tonumber(l, i));
            default:  /* other values */
                printf("%s\n", lua_typename(l, t));
        printf("  ");  /* put a separator */
    printf("\n");  /* end the listing */

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

4 thoughts on “Lua stack dump for c++

  1. Exactly what I needed! Helps alot now when I’m trying to traverse some nested tables. Thanks!

  2. Pingback: E-sitesweb » c/c++ programming by examples

Leave a Reply

Your email address will not be published. Required fields are marked *