lua-users home
lua-l archive

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


2014-11-25 12:57 GMT+00:00 Kang Hu <hukangustc@gmail.com>:
> 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?

It's quite hard to explain if it's not obvious. It has to do with the
difference between values, variables and fields.

First, just so we're clear, in a.a.a.a, there are two kinds of a. One
is a variable (the left-most), and the others are field names.

In Lua there are two kinds of assignments: variable assignment and
field assignment. If you have "name = value", it's a variable
assignment. If you have "value.name = value" or "value[value] =
value", then it's a field assignment. The only other case ("value =
value") is invalid. And one type of assignment can never become the
other type of assignment (if you ignore environment tables).

Since "a.a.a.a" is not a name, "a.a.a.a = 3" must be a field
assignment, and thus it cannot assign a new value to any variable
(again minus environment effects). The assignment will be partially
evaluated until it becomes "x[y] = z" where x, y and z are values, and
at that point it will try to assign a field in value x. In this
example the value x is the table you created on the first line, the
value y is the string "a", and the value z is the number 3 ; no
variable is involved and a will continue to point at the table. What
changes is the content of the table: it goes from being {["a"] =
<itself>} to being {["a"] = 3}.