• Subject: Re: Lua stack clean
• From: Ranier Vilela <ranier.vf@...>
• Date: Wed, 24 Feb 2021 22:51:45 -0300

Thanks, I will test like this.

regards,
Ranier Vilela

Em qua, 24 de fev de 2021 10:47 PM, Sean Conner <sean@conman.org> escreveu:
It was thus said that the Great Ranier Vilela once stated:
> Hi Hackers,
> How should the stack look after the calls below?
>
>     lua_pushinteger(L, p1);
>     lua_pushinteger(L, p2);
>     lua_pushinteger(L, p3);
>     lua_pushnumber(L, p4);
>     lua_call(L, 4, 1);
>     if (lua_isuserdata(L, -1)) {
>         value = lua_tonumber(L, -1);
>         lua_pop(L, 1);
>     }
>     lua_pop(L, lua_gettop(L));
>
> What is the correct way to clean the stack?

The lua_call() function is defined as:

void lua_call(lua_State *L,int nargs,int nresults);

The manual states that lua_call() will remove nargs+1 items from the stack,
and push nresults on the stack.  So for your example:

lua_pushcfunction(L,myfunc);
lua_pushinteger(L,p1);
lua_pushinteger(L,p2);
lua_pushinteger(L,p3);
lua_pushinteger(L,p4); /* [1] */
lua_call(L,4,1);       /* [2] */

At point [1], the stack looks like:

+index  -index  value
----------------------
n-1     -6      previous entries...
n       -5      myfunc
n+1     -4      p1
n+2     -3      p2
n+3     -2      p3
n+4     -1      p4

At point [2], the stack will look like:

+index  -index  value
----------------------
n-1     -2      previous entries...
n       -1      result

In your example, the code should be:

if (lua_is<type>(L,-1))
{
value = lua_to<type>(L,-1);
/* use the value */
}
lua_pop(L,1);   /* remove result from stack */

-spc