Game Development Reference
In-Depth Information
Functions
LuaPlus provides a few ways to call Lua functions from C++. The easiest way is to
use the overloaded template LuaFunction functor class, which makes calling Lua
functions look a lot like calling any C++ function. It takes care of all the parameter
and return value conversions as well. For example, let
'
s say we have the following Lua
function:
function Square(val)
return val * val
end
To call this function from C++, you would do the following:
LuaPlus::LuaState* pLuaState; // assume this is valid
LuaPlus::LuaFunction<float> LuaSquare = pLuaState->GetGlobal(
Square
);
float result = LuaSquare(5);
cout << result; // this will print out 25
The LuaFunction template parameter defines the return value. The parameters are
determined by what you pass when you call the functor. There are a number of over-
loaded templated call operators so that nearly every combination is supported, up to
and including eight different parameters. If you need more than that, you
'
ll need to
use another method for calling Lua functions.
Calling C++ Functions from Lua
Calling a C++ function from Lua requires you to bind that function to the Lua state.
If you were just using the Lua C API, it would require writing a wrapper function
that took the arguments off the stack, translated them into the correct types, and
called the C++ function directly. If you want to bind a C++ instance method, it ' s
even trickier.
Fortunately, LuaPlus takes care of a lot of the headaches for you. All you need to do
is bind your function to a variable in Lua. That variable becomes a Lua function that
can be accessed directly in your Lua code. Simple types are automatically converted,
though there
s still a little translation that needs to happen in the case of tables.
There are several ways to perform this binding with LuaPlus. The simplest way is to
call the RegisterDirect() function on the table you want the function bound to:
'
float Square(float val)
{
return val * val;
}
 
 
 
Search WWH ::




Custom Search