[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Array access indirection
- From: "Matthew Wild" <mwild1@...>
- Date: Sun, 21 Sep 2008 15:09:32 +0100
On Sun, Sep 21, 2008 at 2:53 PM, Tim Channon <tc@gpsl.net> wrote:
> Mark Meijer wrote:
>
>>> require"tprint"
>>>
>>> var="fred"
>>>
>>> pa1="john"
>>> va1="sam"
>>> pa2="ken"
>>> va2="sal"
>>>
>>> rt={}
>>>
>>> rt[var]={[pa1]=va1}
>>>
>>> rt[var]={[pa2]=va2} -- does not add pair
>>> [...]
>>
>> Firstly, for the record, the table constructor notation used here, is
>> the same variant as the one Geoff used above to smack some sense into
>> me ;)
>>
>> The variable var, used as index in the last two statements, resolves
>> to "fred" in both those statements. So, since keys in Lua tables are
>> unique, in the second statement you're simply overwriting the entry
>> you created in the first statement (i.e. the entry named rt.fred). If
>> you change var to something else before the second statement (or in
>> any other way change what the expression used as index there resolves
>> to), then there should be no problem.
>
> 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.
>
It's not *that* hard. Understanding exactly what you are trying to do
is the hardest part :)
t = {}; <-- create a table
k = "hello"
t[k] = { a = 1, b = 2} <-- put a entry in that table, key "hello" and
value is a table
k = "goodbye"
t[k] = { a = 2, b = 1} <-- put a entry in that table, key "goodbye"
and value is a table
We now have a table with 2 key/table pairs. Is this not what you want?
If you don't get this then I suggest you go back to basics, and read
http://lua.org/pil/ or get the book.
Hope this helps,
Matthew.