Game Development Reference
In-Depth Information
you are using the map section. This is done mostly for optimization reasons, as Lua
uses a true array for the array section and a hash map for everything else. This typi-
cally only comes into play when you want to loop through all the elements of a table,
which you
'
ll see below. Note that all tables have these sections, so there
'
s nothing
stopping you from using both in a single table.
In the first example, a table was initialized with the first five prime numbers. You can
also initialize tables that use non-integer keys by wrapping the key in square brackets
and using the assignment operator. The messy table above could be created like this,
assuming that anotherTable and X were already defined:
messyTable = { [“string”] = 20, [“another string”]=“data”,
[anotherTable] = 5, [X] = anotherTable }
You can actually do both:
temp = { [
hat
]=
blue
,5,
purple
,[
ninja
]=3}
This is equivalent to:
temp = {}
temp[
hat
]=
blue
temp[1] = 5
temp[2] =
purple
temp[
]=3
Indexing a table by string is so common that Lua provides a bit of syntax sugar to
make it a little cleaner. First, you don
ninja
t have to surround string keys with square
brackets or quotes when initializing the table. Second, you can access the value by
using the
'
operator with no quotes. These two tables are identical, and the two
print statements show two different ways to access them:
.
v1={[
x
] = 13.5, [
y
]=1,[
z
] = 15.4 }
v2 = { x = 13.5, y = 1, z = 15.4 }
print(v1[
x
]) -- > prints 13.5
print(v1.x)
> prints 13.5
v1.y = 3 -- you can set values using the
-
'
.
'
operator as well
Lua provides a special table named
table
that contains a number of helper functions
for table manipulation. I
m not going to go into detail on these functions, since you
can look them up pretty easily, but here ' s the one-line description for each:
'
n insert() : Inserts elements into the table.
n remove() : Removes elements from the table.
n getn() : Returns the number of elements in the array section of the table (not
including the map section).
Search WWH ::




Custom Search