Game Development Reference
In-Depth Information
it. It checks the new table for a field called y , followed by a metatable, and so on until
it either finds a valid value or can ' t find anything valid, in which case it returns nil .
It
s important to note that this only affects the reading of a value, not the writing of
one. There
'
s invoked when attempting
to write a new value. This is invoked first, before writing the value, to allow you to
change how the table deals with new values. This could be used to implement a read-
only table, for example.
For our vector example, we want to create a template of functionality. We do this by
creating the vector table just as before. This will be our class. To instantiate an object
from this class, a new table is created with a metatable that has an __index field
pointing to the vector class. Here
'
s a separate metamethod, __newvalue , that
'
'
s the new version with an example:
-- Renaming this table to make it look more like a class
Vec3 =
{
-- These values now represent defaults
x=0,y=0,z=0
}
-- This function is unchanged
function Vec3:Length()
return math.sqrt((self.x * self.x) + (self.y * self.y) + (self.z * self.z));
end
-- Create an instance of this class. v is initialized with an __index
-- field set to the Vec3 table.
v = { __index = Vec3 }
setmetatable(v, v) -- v is now its own metatable
-- This will cause Lua to search v for the x field. It won
t find it, so
-- Lua will check for a metatable. It will find out that v is the metatable
-- for v, so it will look for an __index field. It will find one that points
-- to the Vec3 table. Lua will then search Vec3 for an x field, which it finds
-- and returns. The below line will print 0.
print(v.x)
'
-- This assignment will cause Lua to search v for a metatable, which is has.
-- It will then search for a __newindex field, which doesn't exist. Lua will
-- set the value of v.x to 10 without affecting the Vec3 table.
v.x = 10
-- This will cause Lua to search v for the x field, which it finds and returns.
-- It will print 10.
print(v.x)
Search WWH ::




Custom Search