Reputation: 25789
In Lua when I created a table the following way...
test={}
test = { x=5 , y = test.x}
print(test.y)
I expected that test.y would be 5, it is not. Why?
Upvotes: 1
Views: 3287
Reputation: 170308
From Programming in Lua, 2nd ed., page 23, chapter 3.6 Table Constructors:
... That is, all tables are created equal; constructors affect only their initialization. Every time Lua evaluates a constructor, it creates and initializes a new table. ...
So, the table constructor { x=5 , y = test.x }
first creates a new table object, which, after fully being evaluated (!) gets assigned to name test
.
This is what more or less happens in your code:
test = {}
TEMP_TABLE = { x=5 , y=test.x } --> x=5, y=nil
test = TEMP_TABLE
Upvotes: 3
Reputation: 9559
That's simply because test.x only exists after tat statement has been executed. So this would work:
test={}
test.x=5
test.y=test.x
so where you do
test={x=5,y=test.x}
you actually replace the table you generated with t={}
with a new one, and take the value of the key x in the old one, which is nil.
Upvotes: 2