c++ - 如何查找lua堆栈中有多少项(值)

标签 c++ lua stack lua-api

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

最佳答案

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;

关于c++ - 如何查找lua堆栈中有多少项(值),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66435317/

相关文章:

c++ - 在 C++ 中求解两个具有两个未知数的非线性方程

c - Lua 库中奇怪的 C 语法

c - 在 C 中运行 Unreached 代码

c++ - 类似于 std::shared_ptr 中的 "cast from/to void"

c++ - 将属性表升级到 Visual Studio 2010

c++ - Makefile 总是重新编译

lua - 为什么我们需要调用Lua的collectgarbage()两次?

javascript - 平滑旋转到一个 Angular

java - 使用堆栈的这段代码的输出是什么?

c++ - 尝试访问 std::stack 的索引