How to register C++ functions
Lua is written in C, so it cannot access your C++ classes directly. The only way to call C++ code from Lua is to make it call C++ functions – that is, plain C functions.
How to declare C++ functions for Lua
To register a function to Lua, it must conform to the following prototype:
typedef int (*lua_CFunction) (lua_State *L);
The function receives only one argument, which is a Lua state. It needs to return an integer value indicating how many return values it produces. The Lua state is private to the function call, and its stack holds the arguments passed from the Lua code when calling the C++ function. The C++ function needs to push its return values onto the stack.
We will first implement a simple function and export it to Lua. Then, we’ll see more complex examples to understand more.
Implementing your first C++ function for Lua
Let us add a simple but useful capability to our Lua executor. It will provide a function...