Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top