Lua初始化表
在 Lua 中,当我按以下方式创建表时...
test={}
test = { x=5 , y = test.x}
print(test.y)
我预计 test.y 将为 5,但事实并非如此。为什么?
In Lua when I created a table the following way...
test={}
test = { x=5 , y = test.x}
print(test.y)
I expected that test.y would be 5, it is not. Why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
来自Lua 编程,第二版。 ,第 23 页,章节 3.6 表构造函数:
因此,表构造函数
{ x=5 , y = test.x }
首先创建一个新的表对象,在完全评估后(!),该对象被分配给名称test
。您的代码中或多或少会发生以下情况:
From Programming in Lua, 2nd ed., page 23, chapter 3.6 Table Constructors:
So, the table constructor
{ x=5 , y = test.x }
first creates a new table object, which, after fully being evaluated (!) gets assigned to nametest
.This is what more or less happens in your code:
这只是因为 test.x 仅在执行 tat 语句后才存在。所以这是可行的:
因此,
您实际上将使用
t={}
生成的表替换为新表,并获取旧表中键 x 的值,即 nil。That's simply because test.x only exists after tat statement has been executed. So this would work:
so where you do
you actually replace the table you generated with
t={}
with a new one, and take the value of the key x in the old one, which is nil.