lua-users home
lua-l archive

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



On 25.11.2014 13:57, 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?

a.a is equivalent to a["a"], so:
a.a.a.a == a["a"]["a"]["a"] == a["a"]
So no matter how long is your sequence of ".a.a.a", you still get the
same a["a"] (often written as a.a)

> 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?

a.a.a.a = 3 <=> a["a"]=3

> 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?

You still have just one table a, and you seem to confuse it with
multi-level tree like this:

a={a={a={a=3}}}}

Then you would have:

type(a.a.a)=='table'
a.a.a.a==3

Note that now you have created 3 tables, not just one.

Regards,
	miko