Next: 5.6 Locking Lua Objects Up: 5 The Application Program Previous: 5.4 Calling Lua Functions

5.5 C Functions

To register a C function to Lua, there is the following macro:
#define lua_register(n,f)       (lua_pushcfunction(f), lua_storeglobal(n))
/* char *n;         */
/* lua_CFunction f; */
which receives the name the function will have in Lua, and a pointer to the function. This pointer must have type lua_CFunction, which is defined as
typedef void (*lua_CFunction) (void);
that is, a pointer to a function with no parameters and no results.

In order to communicate properly with Lua, a C function must follow a protocol, which defines the way parameters and results are passed.

To access its arguments, a C function calls:

lua_Object     lua_getparam             (int number);
where number starts with 1 to get the first argument. When called with a number larger than the actual number of arguments, this function returns LUA_NOOBJECT. In this way, it is possible to write functions that work with a variable number of parameters.

To return values, a C function just pushes them onto the stack, in direct order; see Section 5.2. Like a Lua function, a C function called by Lua can also return many results.

Section 7.5 presents an example of a CFunction.


Next: 5.6 Locking Lua Objects Up: 5 The Application Program Previous: 5.4 Calling Lua Functions