• Announcement: Lua.org now officially recommends this forum as a meeting place for the Lua community

Basic question about tables in Lua (1 Viewer)

Rooind

Newcomer
Joined
Jul 3, 2021
Messages
3
Reaction score
0
Hi,

In the book "Programming in Lua, 4th edition", there's a question about tables. It's got me a little confused. Here it is:

Assume the following code:
a = {}
a.a = a

(a) What would be the value of a.a.a.a?
(b) Is any a in that sequence somehow different from the others?

Now, add the next line to the previous code:
a.a.a.a = 3

(c) What would be the value of a.a.a.a now?

My understanding of `a.a = a` is that now table `a` has a member called `a` which is a reference to the table itself. I think of references in Lua as behaving like dereferenced pointers. So we effectively have a member that points to the structure itself, and that's my answer to part (a).

It doesn't matter if we do `a.a.a.a.a.a.a.a.a` and so on, this is just the structure itself. So my answer to part (b) is "No."

I'm not sure about part (c) though. Would be grateful for some help. (And please correct my answers to (a) and (b) if I'm wrong about them...)

Thanks.
 

stetre

Member
Rank: I
Joined
Jan 8, 2020
Messages
89
Reaction score
49
Location
Italy
Website
github.com
One nice thing about languages like Lua is that they are easy to experiment with. Try this:

Lua:
a = {}
a.a = a
a.a.a.a = 3
print(a)
print(a.a)  -- <-----  !!!
print(a.a.a.a)
 
Last edited:

Rooind

Newcomer
Joined
Jul 3, 2021
Messages
3
Reaction score
0
One nice thing about languages like Lua is that they are easy to experiment with. Try this:

Lua:
a = {}
a.a = a
a.a.a.a = 3
print(a)
print(a.a)  -- <-----  !!!
print(a.a.a.a)
Yes I think I see it now. But actually, I'm probably more confused. It seems that if we do `a.a.a.a = 3` we're actually doing `a.a =3`, and so trying to access `a.a.a` or `a.a.a.a` (and so on) afterwards means that we're reaching for parts of the table that have not yet been defined.
 

stetre

Member
Rank: I
Joined
Jan 8, 2020
Messages
89
Reaction score
49
Location
Italy
Website
github.com
You talked about references, which is ok, but maybe in Lua it's better to talk about names and values, and read nested names starting from the innermost (or rightmost).

After the first two lines, you have that a.a, a.a.a, a.a.a.a, a.a.a.a.a and so on are all synonyms for a.a. That is, the field named 'a' of the table assigned to the variable a, whose value is the table itself. For example, a.a.a.a is the same as a.a.a['a'].

At the third line you then assign it the number 3, so what you get is just a = { a=3 }. All the synonyms get broken at once, and what you are left with are just a, whose value is the table, and its field a.a, whose value is the number 3.

If you now try to acces, for example, a.a.a, you get an error because what you are trying to access is the field 'a' of the value of a.a, which is a number.
 
Top