如何查找 Lua 堆栈中有多少项(值)

我正在使用 Lua 在 C++ 中工作,我想查找 Lua 堆栈中使用了多少个"slots"(可以这么说),如果可能的话,Lua 堆栈的大小是多少?

点赞
用户15284751
用户15284751

lua_gettop(lua_State* L)

栈中元素的数量与顶部槽位的索引相同。如果你有兴趣,这里有一个会利用此信息打印整个栈的函数:

int top = lua_gettop(L);

std::string str = "从顶部到底部,Lua 栈为:\n";
for (unsigned index = top; index > 0; index--)
{
    int type = lua_type(L, index);
    switch (type)
    {
        // 布尔值
        case LUA_TBOOLEAN:
            str = str + (lua_toboolean(L, index) ? "true" : "false") + "\n";
            break;

        // 数字
        case LUA_TNUMBER:
            str = str + std::to_string(lua_tonumber(L, index)) + "\n";
            break;

       // 字符串
        case LUA_TSTRING:
            str = str + lua_tostring(L, index) + "\n";
            break;

        // 其他类型
        default:
            str = str + lua_typename(L, type) + "\n";
            break;
    }
}

str = str + "\n";
std::cout << str;
2021-03-02 09:30:20