Search code examples
c++luastacklua-api

How to find how many items(values) are in lua stack


I'm working with lua in C++ and I want to find how many "slots"(you can say) are being used in lua stack, and if possible, what is the size of lua stack?


Solution

  • lua_gettop(lua_State* L)

    The number of elements in the stack is the same as the index of the top slot. If you are interested here is something that will print the whole stack for you using this information.

    int top = lua_gettop(L);
    
    std::string str = "From top to bottom, the lua stack is \n";
    for (unsigned index = top; index > 0; index--)
    {
        int type = lua_type(L, index);
        switch (type)
        {
            // booleans
            case LUA_TBOOLEAN:
                str = str + (lua_toboolean(L, index) ? "true" : "false") + "\n";
                break;
    
            // numbers
            case LUA_TNUMBER:
                str = str + std::to_string(lua_tonumber(L, index)) + "\n";
                break;
    
           // strings
            case LUA_TSTRING:
                str = str + lua_tostring(L, index) + "\n";
                break;
    
            // other
            default:
                str = str + lua_typename(L, type) + "\n";
                break;
        }
    }
    
    str = str + "\n";
    std::cout << str;