【问题标题】:Is it allowed to modify stack values as long as the stack stays balanced?只要堆栈保持平衡,是否允许修改堆栈值?
【发布时间】:2017-11-28 01:39:50
【问题描述】:

每个人都知道保持堆栈平衡是一种很好的编程习惯。不过,我想知道的是,是否允许我在从 Lua 脚本调用的 C 函数中修改堆栈值?考虑以下代码:

int myfunc(lua_State *L)
{
    int arg1 = luaL_checkinteger(L, 1);
    int arg2 = luaL_checkinteger(L, 2);

    // pop arg 2
    lua_pop(L, 1);

    // this is to be our return value
    lua_newtable(L);

    ...do complicated stuff...

    // restore second parameter but set it to nil for convenience's sake
    lua_pushnil(L);
    lua_insert(L, 2);

    // return our table
    return 1;
}

所以上面的代码将第二个参数替换为 nil。这是允许的还是我必须恢复原始值,即我必须这样做

lua_pushinteger(L, arg2);

而不是

lua_pushnil(L);

?或者,只要myfunc 返回时堆栈平衡,这无关紧要吗?

【问题讨论】:

    标签: lua


    【解决方案1】:

    堆栈值是被调用的 C 函数的属性。你可以对他们做任何你想做的事。对外部的唯一影响是函数返回的值。

    从 Lua 调用的 C 函数不需要保持堆栈平衡,也就是说,在进入时具有相同的内容或项数。

    【讨论】:

      猜你喜欢
      • 2014-01-10
      • 2016-05-06
      • 1970-01-01
      • 2011-10-10
      • 2011-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多