Game Development Reference
In-Depth Information
Lua calling C/C++ functions
Exposing C++ functions to Lua takes place through a process called function binding. Any
bound functions exposed to Lua become accessible either as a global function or as a func-
tion available through a package. Packages in Lua are similar to namespaces in C++ and
are implemented as a global table within Lua.
Function binding
Any function exposed to Lua must fit the lua_CFunction declaration. A
lua_CFunction declaration takes in the Lua virtual machine and returns the number of
return values pushed onto the Lua stack:
lua.h
typedef int (*lua_CFunction) (lua_State *L);
For example, the C++ GetRadius function exposed in the sandbox is declared in the
LuaScriptBindings.h header file in the following manner:
LuaScriptBindings.h
int Lua_Script_AgentGetRadius(lua_State* luaVM);
The actual function implementation is defined within the LuaScriptBindings.cpp
file and contains the code for retrieving and pushing values back to the stack. The GetRa-
dius function expects an agent pointer as the first and only parameter from Lua and re-
turns the radius of the agent. The Lua_Script_AgentGetRadius function first
checks the stack for the expected parameter count and then retrieves the userdata off the
stack through a helper function within the AgentUtilities class. An additional helper
function performs the actual work of calculating the agent's radius and pushes the value
back onto the stack:
LuaScriptBindings.cpp
int Lua_Script_AgentGetRadius(lua_State* luaVM)
{
if (lua_gettop(luaVM) == 1)
{
Search WWH ::




Custom Search