Game Development Reference
In-Depth Information
public:
void SetPosition(float x, float y, float z);
static LuaObject CreateFromScript(void); // new function on the Ninja class
};
LuaObject Ninja::CreateFromScript(void)
{
// create the C++ instance
Ninja* pCppInstance = new Ninja();
// create the Lua instance
LuaObject luaInstance;
luaInstance.AssignNewTable(pLuaState);
// assign the C++ instance pointer to the lua instance
luaInstance.SetLightUserData(
“
__object
”
, pCppInstance);
// assign the metatable to the new Lua instance table
LuaObject metaTable =
pLuaState->GetGlobalVars().GetByName(“NinjaMetaTable”);
luaInstance.SetMetaTable(metaTable)
return luaObject;
}
The
CreateFromScript()
function also needs to be registered to Lua.
LuaObject globals = pLuaState->GetGlobals();
globals.RegisterDirect(
“
CreateNinja
”
, &Ninja::CreateFromScript);
Now you can create instances of the
Ninja
class in Lua and call the
SetPosition()
function just like you would any other Lua object.
ninja = CreateNinja()
ninja:SetPosition(10, 20, 30)
These two methods of function and object registration form the basis of the glue
between C++ and Lua.
In this next section, I
ll show you how to bring all of these components together to
form a cohesive scripting system. I
'
ll show you how to manage the
LuaState
object
and initialize the scripting system, how to send events to and receive events from the
Event Manager, and how to write your own processes that run inside Lua. This sec-
tion builds on everything you
'
ve learned in this topic so far.
'