RedPolygon
RedPolygon

Reputation: 63

Use table key inside same (anonymous) table

I want to use a key insde an anonymous table from within that same table, like so:

loadstring( [[return {
  a = "One",
  b = a.." two"
}]] )

From my perspective, this should return the following table:

{ a = "One", b = "One two" }

However, it just returns nil. Is this possible to do, and how?

Upvotes: 2

Views: 847

Answers (2)

Paul Kulchenko
Paul Kulchenko

Reputation: 26744

As the other answer said, you can't reference a key in a table that is being constructed, but you can use a variable to hold the value you want to reference several times:

local a = "One"
local t = { a = a, b = a.." two" }

Upvotes: 5

Adam
Adam

Reputation: 3103

No, you can't do that. At the point you are using a the table has not been constructed. Lua looks for a global variable a, which is why you get nil.

If you want to refer to keys in a table they must be defined first.

local t = { a = 'One' }
t.b = t.a..' two'

Upvotes: 2

Related Questions