Game Development Reference
In-Depth Information
'
is used internally in some cases when accessing the leaf table is necessary. It
s cur-
rently used by the
ScriptProcess
class in C++, which you
'
ll see later in this
chapter.
The first thing the
Create()
function does is declare a local variable called
obj
.
This will be the instance table of the class. The next section will recursively call into
the
Create()
function of each base class in the inheritance chain, passing in the
construction data and the original leaf class (which is
self
the first time). When it
finally reaches the top base class,
obj
is initialized with either the
construction-
Data
table or an empty table if there is no construction data. After that, the metata-
ble is set up, and any overloaded operators defined in a special
__operators
table
are copied over. Finally, the object is returned.
Using the
class()
function is a breeze. Here
'
s how you would define the
Vec3
class
above:
Vec3 = class(nil,
{
x=0,y=0,z=0
})
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 = Vec3:Create()
-- This version initializes the values
V2 = Vec3:Create({x = 10, y = 10, z = 10})
It doesn
'
t get much easier than that! Later in this chapter, I
'
ll even show you how you
can inherit from C++ classes.
Public/Private Variable Naming Conventions
One thing you can
t easily get in Lua is a way to represent public, private, and
protected variables. A typical convention in many scripting languages is to put
an underscore in front of variable and function names that are meant to be
private, so seeing
_var
would let the programmer know that this variable is
meant to be private. Similarly, a function named
_Update()
would be a
private function.
'
s good to have this kind of convention, or it quickly
becomes confusing what
It
'
the public interface is. Refactoring can be a
nightmare.