如何将 table 定义中的项目分配给同一 table 中的另一个项目?
How to assign an item in a table definition to another item within the same table?
我试图将 table 的大括号定义中的一个项目分配给之前定义的另一个项目。但是 Lua 说一旦在它的定义中引用它就找不到 table 本身。
这是我要实现的目标的示例:
local t = {
a = 1,
b = 2,
c = t.a + t.b
}
一旦接近t.a
,Lua将无法找到t
并回复错误。
如何在 t
中定义 c
时引用 t.a
和 t.b
而不离开大括号定义 ?
尴尬,但是:
local t
do
local a = 1
local b = 2
t = {a, b, c = a + b}
end
print(t.c) -- 3
没有 do/end
块,a
和 b
变量将在 t
.
之外可见
据我所知,没有直接的方法来引用 a
和 b
,除非 1) 这些变量事先存在(以上示例)或 2) 一旦 table施工完成。
正如你所提的问题,你不能。
"The order of the assignments in a constructor is undefined."
因此,"defined previously" 不是 table 构造函数中的概念。
还有,“The scope of a local variable begins at the first statement after its declaration”。
因此,无法引用您代码中语句结束前显示的局部变量t
。 t
将绑定到先前声明的变量或名为 t
.
的全局变量
我试图将 table 的大括号定义中的一个项目分配给之前定义的另一个项目。但是 Lua 说一旦在它的定义中引用它就找不到 table 本身。
这是我要实现的目标的示例:
local t = {
a = 1,
b = 2,
c = t.a + t.b
}
一旦接近t.a
,Lua将无法找到t
并回复错误。
如何在 t
中定义 c
时引用 t.a
和 t.b
而不离开大括号定义 ?
尴尬,但是:
local t
do
local a = 1
local b = 2
t = {a, b, c = a + b}
end
print(t.c) -- 3
没有 do/end
块,a
和 b
变量将在 t
.
据我所知,没有直接的方法来引用 a
和 b
,除非 1) 这些变量事先存在(以上示例)或 2) 一旦 table施工完成。
正如你所提的问题,你不能。
"The order of the assignments in a constructor is undefined."
因此,"defined previously" 不是 table 构造函数中的概念。
还有,“The scope of a local variable begins at the first statement after its declaration”。
因此,无法引用您代码中语句结束前显示的局部变量t
。 t
将绑定到先前声明的变量或名为 t
.