lua-users home
lua-l archive

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


On 11/25/2014 01:57 PM, Kang Hu wrote:
In Programming in Lua, Third Edition:

Exercise 2.6: Assume the following code:
a = {};
a.a = a
1. What would be the value of a.a.a.a ? Is any a in that sequence somehow
different from the others?
2. Now, add the next line to the previous code:
a.a.a.a = 3
What would be the value of a.a.a.a now?

my reasoning is
1. a.a.a.a = ((a.a).a).a = (a.a).a = a.a = a
2. with the the previous reasoning, 'a' should be 3.
    but actually, 'a.a' equals 3 and 'a' is a table.
why?

Your mistake is that you disregard that tables are stored as reference in Lua.

a = {}; does not mean that a is the empty table but that a is a reference to an empty table.
a.a = a means that a.a becomes a copy of the reference to that same table.

If you make a similar code in C you would write:
table* a = create_table();
a->set("a", a);

table* aa = a->get("a");

Now that mean that aa != a but *aa == *a
aa and have not the same value but reference the same value.

Now when you reasign a variable in Lua that stores a reference, you don't change the value it points to, but the value of the reference itself:
a.a.a.a = 3
equals to this C code
table* aaa = a->get("a")->get("a)->get("a);
aaa->Set("a", 3);

In the last line, the field a of the table is set to 3, but the original pointer to the table is not touched.

It is important to see that in my C code, there are 3 get calls and one set call.
The statement a.a.a.a = 3 is equivalent to a.get("a).get("a").get("a).set("a", 3), in Lua the last dot of a left hand side _expression_ has a different semantic than the other ones.
This can easily be proven by printing out the calls to __index and __newindex when using a metatable.

--
Thomas