Next: 5.5 C Functions Up: 5 The Application Program Previous: 5.3 Manipulating Lua Objects

5.4 Calling Lua Functions

Functions defined in Lua by a chunk executed with dofile or dostring can be called from the host program. This is done using the following protocol: first, the arguments to the function are pushed onto the Lua stack (see Section 5.2), in direct order, i.e., the first argument is pushed first. Again, it is important to emphasize that, during this phase, no other Lua function can be called.

Then, the function is called using

int            lua_call                 (char *functionname);
or
int            lua_callfunction         (lua_Object function);
Both functions return an error code: 0, in case of success; non zero, in case of errors. Finally, the returned values (a Lua function may return many values) can be retrieved with the macro
lua_Object     lua_getresult             (int number);
where number is the order of the result, starting with 1. When called with a number larger than the actual number of results, this function returns LUA_NOOBJECT .

Two special Lua functions have exclusive interfaces: error and setfallback . A C function can generate a Lua error calling the function

void lua_error (char *message);
This function never returns. If the C function has been called from Lua, the corresponding Lua execution terminates, as if an error had occurred inside Lua code. Otherwise, the whole program terminates.

Fallbacks can be changed with:

lua_Object lua_setfallback (char *name, lua_CFunction fallback);
The first parameter is the fallback name, and the second a CFunction to be used as the new fallback. This function returns a lua_Object , which is the old fallback value, or nil on fail (invalid fallback name). This old value can be used for chaining fallbacks.

An example of C code calling a Lua function is shown in Section 8.10.


Next: 5.5 C Functions Up: 5 The Application Program Previous: 5.3 Manipulating Lua Objects