Game Development Reference
In-Depth Information
One way to manage this is as follows:
local cat_01 = animal.new("cat")
local mouse_01 = animal.new("mouse")
animal.move(cat_01)
animal.move(mouse_01)
This might work for some; however, an alternative method to manage this would be the following:
local cat_01 = animal.new("cat")
local mouse_01 = animal.new("mouse")
cat_01:move()
mouse_01:move()
Further, if you had this in an array of animals, you could just about as easily have something like this:
local i
for i=1,#aryAnimals do
aryAnimals[i]:move()
end
Or you could very well also use something like
aryAnimals[i].move(aryAnimals[i])
Notice here how the function is invoked using the dot (
.
) or the colon (
:
). This is something a lot
of beginning Lua developers come across, and they often have questions about the difference
between, say,
cat_01:move()
and
cat_01.move()
. The following section will describe the differences.
The Difference Between . and :
In the preceding example, there's no difference between calling
cat_01.move()
and
cat_01:move()
.
But let's consider that in the same function we also need to pass a parameter
speed
, which indicates
how fast the animal should move. So we simply pass the
speed
as a parameter as
cat_01:move(10)
or
cat_01.move(10)
This on the face of things seems right, but will produce two very different results. The reason is that
when we use the
.
, we are telling Lua to invoke the function that is a member of the object (table),
and when we use the
:
, we are telling Lua to do this and we're also passing the function an unseen
parameter of itself. So when we call the function with
:
, we are passing it two parameters: the first
being the object itself and the second being the speed. With the
.
method, on the other hand, we
pass it only one, which is the speed. Let's look at how it is defined in code (see Figure
2-1
).