Game Development Reference
In-Depth Information
Creating custom userdata
While the sandbox uses userdata to pass around agents and the sandbox itself, another use
of userdata is to add basic primitives into the sandbox. These primitives are completely
controlled by Lua's garbage collector.
The vector primitive added into the sandbox is a good example of using userdata that is
completely controlled by Lua. As a vector is essentially a struct that only holds three val-
ues, it is a great choice for Lua to completely maintain the creation and destruction of the
data. What this means to the C++ code interacting with Lua vectors is that code should
never hold on to the memory address returned from Lua. Instead, the code should copy val-
ues retrieved from Lua and store them locally.
Looking at the vector data type
Elevating a vector into a basic Lua primitive means supporting all the expected operations
users would like to perform on a vector variable in Lua. This means that vectors should
support the addition, subtraction, multiplication, indexing, and any other basic operators
supported by Lua.
To accomplish this, the vector data type uses metamethods to support basic arithmetic oper-
ators, as well as supporting the dot operator for the ".x", ".y", and ".z" style syntax:
LuaScriptUtilities.cpp
const luaL_Reg LuaVector3Metatable[] =
{
{ "__add", Lua_Script_Vector3Add },
{ "__div", Lua_Script_Vector3Divide },
{ "__eq", Lua_Script_Vector3Equal },
{ "__index", Lua_Script_Vector3Index },
{ "__mul", Lua_Script_Vector3Multiply },
{ "__newindex", Lua_Script_Vector3NewIndex },
{ "__sub", Lua_Script_Vector3Subtract },
{ "__tostring", Lua_Script_Vector3ToString },
{ "__towatch", Lua_Script_Vector3ToWatch },
{ "__unm", Lua_Script_Vector3Negation },
{ NULL, NULL }
};
Search WWH ::




Custom Search