3.14 – Calling Functions
Functions defined in Lua and C functions registered in Lua can be called from the host program. This is done using the following protocol: First, the function to be called is pushed onto the stack; then, the arguments to the function are pushed in direct order, that is, the first argument is pushed first. Finally, the function is called using
- void lua_call (lua_State *L, int nargs, int nresults);
nargs
is the number of arguments that you pushed onto the stack. All arguments and the function value are popped from the stack, and the function results are pushed. The number of results are adjusted to nresults
, unless nresults
is LUA_MULTRET
. In that case, all results from the function are pushed. Lua takes care that the returned values fit into the stack space. The function results are pushed onto the stack in direct order (the first result is pushed first), so that after the call the last result is on the top.
The following example shows how the host program may do the equivalent to this Lua code:
- a = f("how", t.x, 14)
Here it is in C:
- lua_pushstring(L, "t");
- lua_gettable(L, LUA_GLOBALSINDEX); /* global `t' (for later use) */
- lua_pushstring(L, "a"); /* var name */
- lua_pushstring(L, "f"); /* function name */
- lua_gettable(L, LUA_GLOBALSINDEX); /* function to be called */
- lua_pushstring(L, "how"); /* 1st argument */
- lua_pushstring(L, "x"); /* push the string "x" */
- lua_gettable(L, -5); /* push result of t.x (2nd arg) */
- lua_pushnumber(L, 14); /* 3rd argument */
- lua_call(L, 3, 1); /* call function with 3 arguments and 1 result */
- lua_settable(L, LUA_GLOBALSINDEX); /* set global variable `a' */
- lua_pop(L, 1); /* remove `t' from the stack */
Note that the code above is “balanced”: at its end, the stack is back to its original configuration. This is considered good programming practice.
(We did this example using only the raw functions provided by Lua’s API, to show all the details. Usually programmers define and use several macros and auxiliary functions that provide higher level access to Lua. See the source code of the standard libraries for examples.)