Calling C++ from Lua
To call C++ code from Lua, the C++ code needs to be exported via a lua_CFunction
implementation, which is defined as follows:
typedef int (*lua_CFunction) (lua_State *L);
For example, in LuaExecutor
, we implemented a function:
int luaGetExecutorVersionCode(lua_State *L) { lua_pushinteger(L, LuaExecutor::versionCode); return 1; }
This returns a single integer value to the Lua code. A simple way to export this function to the global table can be implemented as follows:
void registerHostFunctions(lua_State *L) { lua_pushcfunction(L, luaGetExecutorVersionCode); lua_setglobal(L, "host_version"); }
You can use lua_pushcfunction
to push lua_CFunction
onto the stack and then assign it to a variable of your choice.
However, more than likely, you should export a group of functions as a module.
Exporting C++ modules
To export a C++ module, you simply need...