tables
syntax
If
t is a table, and
k is one of its keys,
then
t[k] is the value of
t at
the key
k. A table is thus like a function
of one argument except that we talk of
keys rather than of
arguments.
It is like a function semantically, but not operationally. In a function-call
time of calculation depends on the value of the argument, whereas time to
lookup in a table is generally independent of the value of the key.
Lua tables are mutable objects. That is to say, they can be
updated (unlike numbers or strings). If
t is a table,
and
k is one of its keys, then an assignment
t[k] = x
will update to
x the value of
t corresponding
to
k. In such a statement all three of
t,
k and
x may be replaced by compound
expressions. If
t has no key
k then the
assignment creates one. A statement
t = {} creates
a new table, an empty one with no keys, and assigns to
the variable
t a pointer to it.
The single statement (whose right hand side is an example of
a
table constructor)
t = { ["heinz"] = 57, [100] = true }
is effectively equivalent to
t = {}
t["heinz"] = 57
t[100] = true
A table's identity is not decided by its keys and values but by its
position in memory. So if we create a second table
w with
w = { ["heinz"] = 57, [100] = true }
then we get
print (t == w) --> false
because
t and
w are distinct tables.
On the other hand:
u = t
print (t == u) --> true
because
t and
u both point at the same
table. Roughly speaking, the number of different tables created by a
program is equal to the number of nested braces (curly brackets) when
the loops in the program are unrolled. So for example
x = { ["left"] = {}, ["right"] = {}}
creates three tables making a treelike structure un memory:
x
/ \
left right
There is nothing to stop a table being a key or a value of itself, or
even both:
x = { [x] = x }
so that in memory we are dealing with graphs (which can have loops)
rather than trees.
The business of cloning, i.e. making a copy of, a table is fraught
with complications. Do we recursively clone values that are tables?
What if there are loops, as in the example above? What about the
keys that are tables - are they to be cloned too?
Tables are the basic datatype of Lua. They are the standard means
of storing values in the heap. Where explicit pointers holding
memory addresses might be used in C or BBC Basic, in Lua tables,
which may have values which are also tables, must be used. The
newcomer to Lua with experience of C should beware, however, of
simply translating C-like pointer structures (e.g. linked lists)
into their Lua-table equivalents. It often turns out that tables
are quite adequate to represent the datatype by themselves.