|
Indeed – the explanation becomes much clearer if you replace the ‘a.a’ which is frankly confusing with
a = {} a.thistable = a
now the original table that we’ve called a contains a reference to itself, stored in the entry ‘thistable’.
It is a lot simpler to then understand that
a.thistable.thistable.thistable
is exactly the same as a.thistable
If you then wrote:
a.thistable = 3
It’s clearly replacing the ‘thistable’ entry with the number ‘3’. So similarly
a.thistable.thistable.thistable = 3
Does exactly the same thing.
The fact they’ve chosen to make the example a little more confusing by awarding the table entry the same name as the global variable doesn’t help (and is a little unnecessary for getting the point across).
-Chris
From: lua-l-bounces@lists.lua.org [mailto:lua-l-bounces@lists.lua.org]
On Behalf Of Axel Kittenberger
This is exactly one of the reasons why a few years ago I switched in my projects to work with immutable types only and simulate immutables with languages that don't have them natively.
Cycles? Do not happen. Point. Brain damage avoided.
It is a nice exercise about understanding the principles, but for any real project, just don't do this kind of back-cycles unless you that surreal case, which somebody now sure comes up to counter me, in which you really need it. I say, one can even work around that surreal case.
PS: As other tried to explain already, all a[.a]* point to the same table. Thus you are always altering the original table and breaking the cycle with it.
On Tue, Nov 25, 2014 at 2:39 PM, Thomas Jericke <tjericke@indel.ch> wrote: 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 = a1. What would be the value of a.a.a.a ? Is any a in that sequence somehowdifferent from the others?2. Now, add the next line to the previous code:a.a.a.a = 3What would be the value of a.a.a.a now?my reasoning is1. a.a.a.a = ((a.a).a).a = (a.a).a = a.a = a2. 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.
Please consider the environment before printing this email :-) This email and any files transmitted with it are confidential and intended solely for the use of the individual or entity to whom they are addressed. If you have received this email in error please notify the sender immediately then delete this email. Any views expressed in this email are solely that of the individual and not representative of the company as a whole. Media Molecule Limited Company Reg No 5665849 Registered in England. ______________________________________________________________________ This email has been scanned by the Symantec Email Security.cloud service. For more information please visit http://www.symanteccloud.com ______________________________________________________________________ |