2

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?

RedPolygon
  • 63
  • 1
  • 9

2 Answers2

5

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" }
Community
  • 1
  • 1
Paul Kulchenko
  • 25,884
  • 3
  • 38
  • 56
2

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'
Adam
  • 3,053
  • 2
  • 26
  • 29