Game Development Reference
In-Depth Information
else
obj = constructionData or {};
end
setmetatable(obj, obj);
obj.__index = self;
-- copy any operators over
if (self.__operators
= nil) then
for key, val in pairs(self.__operators) do
obj[key] = val;
end
end
˜
return obj;
end
return ret;
end
This is probably one of the most complex Lua functions you
s
walk through it step by step. The function takes two parameters. The
baseClass
parameter is the base class for this class. It is expected to be a table that also creates
with the
class()
function. If this class has no base class, you must explicitly pass in
nil
. The
body
parameter is the body of the class. It is expected to be a table where
all of the member variables live.
The first line of the function creates the return value
ret
as a local variable that is
initialized to either the body table (if there is one) or an empty table. This variable
will be the class table itself, much like
Vec3
was earlier. If a base class is passed in,
ret
will be set up as its own metatable with the
__index
field pointing to the base
class. This sets up the inheritance hierarchy.
The next section defines and creates the
Create()
member function, which is used
to instantiate objects from this class. Since the class table is generated by the function,
this function needs to be defined inline like this.
The
Create()
function takes in three parameters. The first parameter is
self
,
which is the class table we
'
ve seen so far, so let
'
re instantiating the object from. This is passed in automat-
ically by using the colon operator when calling it. Since this function is being defined
with the assignment operator, this parameter needs to be explicitly put here. The sec-
ond parameter is
constructionData,
which is a table that can be sent in as extra
data. Think of it like a constructor: any extra data that
'
s sent in will be added to the
instance data, overriding any values from the class. The third parameter,
original-
SubClass
, is a special parameter used for recursion. It must be
nil
. This parameter
'