问题
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?
回答1:
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" }
回答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'
来源:https://stackoverflow.com/questions/38622988/use-table-key-inside-same-anonymous-table