Keeping the stack balanced

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

Keeping the stack balanced

Johansen
The Lua 4.0 manual contains the following (section 5.12): 
http://www.tecgraf.puc-rio.br/lua/manual/manual.html

/Begin
"The following example shows how the host program may do 
the equivalent to the Lua code: 
        a,b = f("how", t.x, 4)
 Here it is in C: 

0
1 lua_getglobal(L, "t");                      /* global `t' (for later use)
*/
2 lua_getglobal(L, "f");                           /* function to be called
*/
3 lua_pushstring(L, "how");                                 /* 1st argument
*/
4 lua_pushstring(L, "x");                            /* push the string `x'
*/
4 lua_gettable(L, -4);                      /* push result of t.x (2nd arg)
*/
5 lua_pushnumber(L, 4);                                     /* 3rd argument
*/
4 lua_call(L, 3, 2);        /* call function with 3 arguments and 2 results
*/
3 lua_setglobal(L, "b");                         /* set global variable `b'
*/
2 lua_setglobal(L, "a");                         /* set global variable `a'
*/
1 lua_pop(L, 1);                               /* remove `t' from the stack
*/

Notice that the code above is ``balanced'': at its end ,the stack is back to
its original 
configuration. This is considered good programming practice. 
/End

The numbers in the left are numbers I have added, showing what I think is
the stacksize *after* 
calling the function to the left. For some reason I end up with 1 element on
the stack 
after the last pop (lua_pop(L,1))

What have I missed?

Regards
Vagn Johansen


Reply | Threaded
Open this post in threaded view
|

Re: Keeping the stack balanced

Roberto Ierusalimschy
The counting of lua_call is wrong:

  4 lua_call(L, 3, 2);     /* call function with 3 arguments and 2 results */
  3 ...

lua_call removes its arguments plus the function been called from the
stack, so after the call the stack will have only 2 elements.

-- Roberto