Game Development Reference
In-Depth Information
Length = function(vec)
return math.sqrt((vec.x * vec.x) + (vec.y * vec.y) + (vec.z * vec.z));
end
}
This technically works:
vector.x = 10
vector.y = 20
vector.z = 15
print(vector.Length(vector)) -- > prints 26.92582321167
There are several things wrong with this object. One glaring issue is that the Length()
function requires the table it is on as a parameter. This idea isn
t completely unreason-
able from a technical point of view; after all, C++ passes the this pointerasahidden
first parameter to all member functions. Fortunately, Lua offers this same functionality.
By replacing the
'
.
with a
:
, Lua passes in the table as the first parameter and calls
it self .
print(vector:Length()) -- > prints 26.92582321167
This works when defining the function, too:
vector =
{
x=0,y=0,z=0
}
-- Note the lack of parameter; since the colon operator is used, self
-- is implied.
function vector:Length()
return math.sqrt((self.x * self.x) + (self.y * self.y) + (self.z * self.z));
end
As you can see, the function is defined using the colon operator. This implies a first
parameter called self , which is implicitly passed in when function is called with the
colon operator. Note that the colon operator is just syntax sugar, because it doesn ' tactu-
ally change anything except to supply that hidden first parameter. It
s perfectly valid to
define a function using the colon operator andcallitbyexplicitlypassingthetableor
vice versa. Another side effect of using the colon operator is the need to declare the func-
tion outside the table. This is the preferred method for assigning functions to tables.
Now we have a vector object that has what appears to be a member function on it.
This is nice, but it doesn
'
'
t get us what we really want. We need a way to define clas-
ses of data and functionality that we can then instantiate objects from. We need a
way to write a class.
 
Search WWH ::




Custom Search