Game Development Reference
In-Depth Information
bind C++ member functions to a special table in Lua without having to specify the
object instance at registration time. This table can serve as the metatable for other
tables that represent instances of the object. It only needs to be created once. When
a new object is sent to the script, a new table is created with that metatable applied.
This new table has a special __object field that contains a lightuserdata pointer
back to the C++ instance. This is how LuaPlus know which C++ instance to invoke
the function on. In Lua, lightuserdata is a type that is ignored by the Lua inter-
preter. It
s a raw pointer that is effectively equivalent to a void* in C++. In fact,
when you retrieve a lightuserdata object in C++, a void* is returned.
Creating this table and binding methods to it are relatively straightforward. You cre-
ate the table as you would any other variable and call RegisterObjectDirect()
for each method you want to bind. As an example, let
'
'
s say you have a very simple
class you want to expose to the script.
class Ninja
{
Vec3 m_position;
public:
void SetPosition(float x, float y, float z);
};
The SetPosition() method is the one you want to expose to the script. Some-
where in the initialization code, the metatable needs to be created, and the function
needs to be registered.
LuaState* pLuaState; // assume this is valid
// create the metatable under the global variable name NinjaMetaTable
LuaObject metaTable = pLuaState->GetGlobalVars().CreateTable(
NinjaMetaTable
);
metaTable.SetObject(
__index
, metaTable); // it
'
s also its own metatable
// register the SetPosition() function
metaTable.RegisterObjectDirect(
SetPosition
, (Ninja*)0, &Ninja::SetPosition);
The metatable now exists in Lua and has the SetPosition() method bound to it.
It can
'
'
s missing the instance pointer. When the object
itself is created, that pointer needs to be bound to a new table, which will serve as the
instance of that object in Lua. One way to do this is to create a new static method
that will instantiate the object, take care of the binding, and return the table with the
C++ instance pointer bound to it.
t be called, of course, since it
class Ninja
{
Vec3 m_position;
Search WWH ::




Custom Search