Use table key inside same (anonymous) table

对着背影说爱祢 提交于 2019-12-31 03:21:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!