首页 > 解决方案 > 如何查找lua堆栈中有多少项目(值)

问题描述

我正在使用 C++ 中的 lua,我想找出在 lua 堆栈中使用了多少“插槽”(你可以说),如果可能的话,lua 堆栈的大小是多少?

标签: c++luastacklua-api

解决方案


lua_gettop(lua_State* L)

堆栈中的元素个数与顶部插槽的索引相同。如果您对此感兴趣,可以使用此信息为您打印整个堆栈。

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;

推荐阅读