The Lua 4.0 manual contains the following (section 5.12):
"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:
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
configuration. This is considered good programming practice.
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
after the last pop (lua_pop(L,1))
What have I missed?
The counting of lua_call is wrong:
4 lua_call(L, 3, 2); /* call function with 3 arguments and 2 results */
lua_call removes its arguments plus the function been called from the
stack, so after the call the stack will have only 2 elements.