Game Development Reference
In-Depth Information
n
setn()
: Sets the number of elements in the array section of the table (not the
map section). This is useful to allow
nil
to exist in a table.
n
maxn()
: Returns the highest positive numerical index of the table by doing a
O(n) search.
n
sort(
): Sorts the array portion of the table.
n
concat()
: Joins the elements of a table together to form a string.
Tables are extremely powerful, especially when you factor in the idea that everything
in Lua is a first-class object, including functions. You can create tables that contain
data and functions indexed by strings using the
“
.
”
operator. At that point, it starts
looking like a real object-oriented language. Once you add in metatables, you have
everything you need to create a fully object-oriented system very easily. I
ll revisit this
concept later on in the chapter after I show you more of the basic operations in Lua.
'
Lua supports a number of control structures that are common in most programming
languages, like
if
,
while
, and
for
.
if
The structure of an
if
statement looks like this:
if exp then
-- do something
end
Unlike C, Lua doesn
t use curly braces for scoping blocks of code. In this case, it uses
the
then
keyword to define the beginning of the block and the
end
keyword to end
it. You can also have
else
and
elseif
statements, which work like they do in C:
'
if exp then
-- do something
elseif exp2 then -- note that elseif is all one word
-- do something else
else
-- otherwise, do this other thing
end -- note how end will end the whole chain and is omitted above
while
while
loops work much like they do in C. Here
'
s the basic form:
i=5
while i>0do