开发者社区 问答 正文

从C,我如何打印Lua堆栈的内容?

我的C程序可能有一个愚蠢的错误。在某些点上,Lua堆栈不包含我认为应该包含的值。

为了对其进行调试,我想在程序的特定位置打印Lua堆栈的内容。如何做到这一点而又不会弄乱堆栈?

展开
收起
kun坤 2019-11-29 11:07:43 905 分享 版权
1 条回答
写回答
取消 提交回答
  • 此代码从上到下遍历堆栈,并调用tostring每个值,打印结果(如果未获得结果,则打印类型名称)。

    assert(lua_checkstack(L, 3));
    int top = lua_gettop(L);
    int bottom = 1;
    lua_getglobal(L, "tostring");
    for(int i = top; i >= bottom; i--)
    {
        lua_pushvalue(L, -1);
        lua_pushvalue(L, i);
        lua_pcall(L, 1, 1, 0);
        const char *str = lua_tostring(L, -1);
        if (str) {
            printf("%s\n", str);
        }else{
            printf("%s\n", luaL_typename(L, i));
        }
        lua_pop(L, 1);
    }
    lua_pop(L, 1);
    
    
    2019-11-29 11:08:00
    赞同 展开评论
问答地址: