3.17 – Defining C Closures

When a C function is created, it is possible to associate some values with it, thus creating a C closure; these values are then accessible to the function whenever it is called. To associate values with a C function, first these values should be pushed onto the stack (when there are multiple values, the first value is pushed first). Then the function

  1. void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n);

is used to push the C function onto the stack, with the argument n telling how many values should be associated with the function (lua_pushcclosure also pops these values from the stack); in fact, the macro lua_pushcfunction is defined as lua_pushcclosure with n set to 0.

Then, whenever the C function is called, those values are located at specific pseudo-indices. Those pseudo-indices are produced by a macro lua_upvalueindex. The first value associated with a function is at position lua_upvalueindex(1), and so on. Any access to lua_upvalueindex(*n*), where n is greater than the number of upvalues of the current function, produces an acceptable (but invalid) index.

For examples of C functions and closures, see the standard libraries in the official Lua distribution (src/lib/*.c).