Game Development Reference
In-Depth Information
p1 = make_pos(5,6)
p2 = make_pos(2,4)
p3 = p1 + p2
print(p3[1], p3[2])
Object-Oriented Lua
Lua is not an object-oriented language, but it has functionality that allows for it to be used like one. I
described this in Chapter 2, where functions can be added to a table, called with the
:
operator, and
passed to the function.
We had a look at
deepcopy
earlier—a way to create a copy of a table other than just passing a pointer to
memory. We also had a look at tweaking the metatable to override some of the functionality of tables.
The logic programming language Prolog has features that help to create relationships and thereby
connections between data, and then look this information up using predicates. In the most basic
manner, Lua can provide similar functionality.
First, here's an example of how we can create the relationships:
-- Create the relationships
company(Jayant, OZApps)
language(CoronaSDK, Lua)
language(GiderosStudio, Lua)
language(Moai, Lua)
language(XCode, ObjectiveC)
-- Query the relationships
print(is_language(CoronaSDK, ObjectiveC))
print(is_company(Jack, OZApps))
print(is_company(Jayant, OZApps))
-- additionally
father(Vader, Luke)
father(Vader, Leia)
brother(Luke, Leia)
sister(Leia, Luke)
print(is_sister(Leia, Luke))
print(is_sister(Leia, Han))
All of this can be run from the terminal. One of the challenges in this is that Lua does not have
commands that help associate these relationships; the first thing you will get if you type
father
(Vader, Luke)
in the terminal window is an error that states that there is no global called
father
.
This happens because there is no function or variable called
father
,
Vader
, or
Luke
. To rectify this
situation, we take the help of metatables. As described previously, whenever Lua tries to retrieve
a missing value, it calls the
__index
function. Let's see what happens when we set an
__index
metamethod and try to invoke
father(Vader, Luke)
:
setmetatable(_G, {__index =
function(tbl, name)