只要堆栈保持平衡,是否可以修改堆栈值? [英] Is it allowed to modify stack values as long as the stack stays balanced?

查看:151
本文介绍了只要堆栈保持平衡,是否可以修改堆栈值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每个人都知道保持堆栈平衡是一种良好的编程习惯.我想知道的是,是否允许我在从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.

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.

这篇关于只要堆栈保持平衡,是否可以修改堆栈值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆