Calling C functions from Lua
Because functions in C and Lua work so differently, exposing a C function to Lua can get a bit tricky. All C functions that Lua can call must follow the signature of lua_CFunction
, which is defined in lua.h
as the following:
typedef int (*lua_CFunction) (lua_State *L);
This function takes only one argument, the lua_State
. The return value of the function is an integer. This integer is the number of elements that the function pushed onto the stack as return values.
Note
Lua has multiple stacks—each C function called from Lua has its own stack and does not share the global stack.
Let's take for example a simple C function that returns the magnitude of a three-dimensional vector. In C, the code for doing so might look something like the following:
double Vec3Magnitude(double x, double y, double z) { double dot = x * x + y * y + z * z; if (dot == 0.0) { return 0.0; } return sqrt(dot); }
The preceding function can't be exposed to Lua directly because...