This first edition was written for Lua 5.0. While still largely relevant for later versions, there are some differences.
The third edition targets Lua 5.2 and is available at Amazon and other bookstores.
By buying the book, you also help to support the Lua project.


26 – Calling C from Lua

One of the basic means for extending Lua is for the application to register new C functions into Lua.

When we say that Lua can call C functions, this does not mean that Lua can call any C function. (There are packages that allow Lua to call any C function, but they are neither portable nor robust.) As we saw previously, when C calls a Lua function, it must follow a simple protocol to pass the arguments and to get the results. Similarly, for a C function to be called from Lua, it must follow a protocol to get its arguments and to return its results. Moreover, for a C function to be called from Lua, we must register it, that is, we must give its address to Lua in an appropriate way.

When Lua calls a C function, it uses the same kind of stack that C uses to call Lua. The C function gets its arguments from the stack and pushes the results on the stack. To distinguish the results from other values on the stack, the function returns (in C) the number of results it is leaving on the stack. An important concept here is that the stack is not a global structure; each function has its own private local stack. When Lua calls a C function, the first argument will always be at index 1 of this local stack. Even when a C function calls Lua code that calls the same (or another) C function again, each of these invocations sees only its own private stack, with its first argument at index 1.