Lua question: table.

Status
Not open for further replies.
Level 11
Joined
Oct 11, 2012
Messages
711
Hey guys, this question is from a book:

JASS:
Assuming the following code:
a = {}; a.a. = a

What would be the value of a.a.a.a ? 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
What would be the value of a.a.a.a now?

The question is kinda confusing to me. :( Thanks in advance of the help.
 
You can easily try this in the lua interactive console:

Code:
> a = {}
> a.a = a
> print(a.a.a.a)
table: 0x17846c0
> print(a.a.a.a.a)
table: 0x17846c0
> print(a.a.a.a.a.a)
table: 0x17846c0
> a.a.a.a = 3
> print(a.a.a.a)
stdin:1: attempt to index field 'a' (a number value)
stack traceback:
	stdin:1: in main chunk
	[C]: in ?
> print(a.a)
3
> print(a)
table: 0x17846c0

a.a references the same table as a and thus you can replace a.a with a. It is the same value, so a.a.a.a = a.a.a = a.a = a.

And a.a.a.a = 3 is actually the same as writing a.a = 3.

After that the line print(a.a.a.a) will fail, because a.a = 3, so the line is equivalent to print(3.a.a). And the number 3 does not have a field named a.

The important concept to understand here is aliasing: Multiple variables can point to the same object and this can cause problems when you do not understand the consequences.
 
If you are more familiar with OOP, it might be easier to look at it like that:

a is an object of class X
class X has a variable named a, with the type X

thus a.a points to the same type as a itself. If you set a.a to a itself, then a.a.a.a.a.a... will still point to a. It's like being your own child. If you say your child's child's child, it's actually yourself, since your child is yourself.

But this is basically the same as the post above, with different words and a bit different approach. I wouldn't say that it's aliasing though - it's more like understanding the concept of pointers.
 
Status
Not open for further replies.
Back
Top