【问题标题】:c calls lua function, the return value is on the stack.Need I pop it?c调用lua函数,返回值在栈上。需要我pop吗?
【发布时间】:2017-09-05 20:49:01
【问题描述】:
  1. 一个lua函数返回两个数字
  2. c++调用lua函数:foo
  3. 不知道是否需要pop函数foo(lua_pop(L,2);)的返回值。
  4. 请告诉我怎么做以及为什么。非常感谢。

部分代码如下:

// lua function
function foo(a, b)
    return a+b, a-b;
end

// c++

lua_getglobal(L,"foo"); // push function
lua_pushnumber(L,1);    // push argument 1
lua_pushnumber(L,2);    // push argument 2

error=lua_pcall(L, 2, 2, 0);

if (!error) {
    printf("return:%s\n",lua_tostring(L,-1));
    printf("return:%s\n",lua_tostring(L,-2));
    // is this needful
    lua_pop(L,2);
}

【问题讨论】:

    标签: lua


    【解决方案1】:

    您应该始终尝试将堆栈保持在已知状态,以防您使用相同的 lua_State 调用更多函数。如果您将结果留在堆栈上并进行更多调用,您最终将填满可用的堆栈空间。

    所以是的,您应该在使用它们的值后将 2 个结果从堆栈中弹出。

    【讨论】:

    • 确实如此。如果你很懒,lua_pop(l, lua_gettop(l)) 会将所有剩余的条目从堆栈中弹出。
    • lua_settop(L, 0) 似乎更习惯于清除堆栈
    猜你喜欢
    • 2016-08-02
    • 2018-09-16
    • 2015-10-08
    • 2011-06-10
    • 2021-12-13
    • 2014-09-06
    • 2016-10-24
    • 2010-10-17
    • 2013-07-14
    相关资源
    最近更新 更多