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

  1. 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:

  1. a = f("how", t.x, 14)

Here it is in C:

  1. lua_pushstring(L, "t");
  2. lua_gettable(L, LUA_GLOBALSINDEX); /* global `t' (for later use) */
  3. lua_pushstring(L, "a"); /* var name */
  4. lua_pushstring(L, "f"); /* function name */
  5. lua_gettable(L, LUA_GLOBALSINDEX); /* function to be called */
  6. lua_pushstring(L, "how"); /* 1st argument */
  7. lua_pushstring(L, "x"); /* push the string "x" */
  8. lua_gettable(L, -5); /* push result of t.x (2nd arg) */
  9. lua_pushnumber(L, 14); /* 3rd argument */
  10. lua_call(L, 3, 1); /* call function with 3 arguments and 1 result */
  11. lua_settable(L, LUA_GLOBALSINDEX); /* set global variable `a' */
  12. 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.)