问题描述
每个人都知道保持堆栈平衡是一种很好的编程习惯.不过,我想知道的是,是否允许我修改从 Lua 脚本调用的 C 函数中的堆栈值?考虑以下代码:
Everybody knows it is good programming practice to keep the stack balanced. What I'm wondering, though, is whether I'm allowed to modify stack values in a C function called from a Lua script? Consider the following code:
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替换了第二个参数.这是允许的还是我必须恢复原始值,即我必须这样做
So the code above replaces the second parameter with nil. Is this allowed or do I have to restore the original value, i.e. would I have to do
lua_pushinteger(L, arg2);
代替
lua_pushnil(L);
?或者只要 myfunc
返回时堆栈平衡,这不重要吗?
? Or doesn't this matter as long as myfunc
returns with the stack balanced?
推荐答案
堆栈值是被调用的 C 函数的属性.你可以对他们做任何你想做的事.对外唯一的影响是函数返回的值.
The stack values are the property of the C function being called. You can do whatever you wish with them. The only effect to the outside is the values returned by the function.
从 Lua 调用的 C 函数不需要保持堆栈平衡,即具有相同的内容或条目数.
C functions called from Lua do not need to keep the stack balanced, that is, with the same contents or number of items it had on entry.
这篇关于只要堆栈保持平衡,是否允许修改堆栈值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!