lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


2008/9/21 Tim Channon <tc@gpsl.net>:
> I find the Lua syntax very difficult and seems to catch many people.
>
> The intention is that rt is a table of key/table pairs
>
> Hence rt[var] is intended to address the table which is the value
> associated with key [var]
>
> Within that subtable I want to add key/value pairs.
>
> Obviously I am doing something wrong but no amount of experimenting or
> reading over weeks has provided a clue on how it can be done.

Ah, then I think Peter's post should provide a clue.

In your code, the line 'rt[var]={[pa1]=va1}' assigns a value to the
entry in table rt with key var. Specifically, the value being assigned
is a newly constructed table, which itself contains a single key/value
pair. The line "rt[var]={[pa2]=va2}" again assigns a newly constructed
table, to the same entry in table rt with key var, i.e. overwriting
the previous value of rt[var]. The curly braces always indicate that a
NEW table is being created.

What you want is to create one table to contains your key/value pairs,
and assign that to rt[var]. One way of doing that is (including some
whitespace for clarity):
rt[var] = {[pa1] = va1, [pa2] = va2}

The same code, but using multiple lines for even more clarity:
rt[var] = {
   [pa1] = va1,
   [pa2] = va2
}

Another way of doing it, which does not entail having all key/value
pairs present together in a single table construction expression, but
otherwise has the exact same result:
rt[var] = {} -- Assign newly constructed empty table to rt[var]
rt[var][pa1] = va1 -- See explanation below.
rt[var][pa2] = va2 -- This line was copied from Peter's post.

Why this works? rt[var] is an L-value expression, returning the entry
from table rt that corresponds to key var. The returned value here is
another table (the empty one created and assigned to rt[var] in the
preceding statement), which is then indexed with key pa1. The L-value
being returned is then assigned the value va1. So, if var="fred" and
pa1="john" and va1="sam", then that statement is equivalent to:
rt["fred"]["john"] = "sam"

or:
mysubtable = rt["fred"]
mysubtable["john"] = "sam"

or, using the syntactic sugar for keys of type string:
rt.fred.john = "sam"

The intuition behind the 'rt[var][pa1]' syntax is not much different
from a regular multidimensional C array. Except that a
multidimensional array in Lua is literally a table of tables (of
tables, of tables, ad inf), is heterogeneous like any other table, can
be jagged, and its dimensions (as well as the number of dimensions)
can change dynamically. But each table within a table *does* need to
be created explicitly. A better way of saying this, is that
multidimensional arrays don't exist in Lua, but they can be simulated
by composing them from individual, 1-dimensional Lua-tables.