我最近一直在查找Lua中的链接列表并有一个快速的问题,到目前为止我还没有找到答案 local head = nilhead = {next = head, value = "d"}head = {next = head, value = "c"}head = {next = head, value = "b"}head = {next
local head = nil
head = {next = head, value = "d"}
head = {next = head, value = "c"}
head = {next = head, value = "b"}
head = {next = head, value = "a"}
local entry = head
while entry do
print(entry.value)
entry = entry.next
end
这将最终打印出“a,b,c,d”.我理解为什么它会向后打印,因为可用的第一个“节点”将是最终创建的(节点值= a).我的问题是为什么在最后一个之前创建的头部仍然存在并且没有被简单地覆盖在内存中.
你在“记忆中被覆盖”是什么意思?你所做的一切都不会导致这种情况发生.让我们一步一步看看你在做什么.
local head = nil
现在存在一个名为head的局部变量.它的值为零.
head = {next = head, value = "d"}
让我们把它分解为这里的操作顺序.这相当于以下内容:
do
local temp = {}
temp.next = head --This is still `nil`
temp.value = "d"
head = temp
end
您构建的每个表都是唯一值.所以我们先把这个表称为d表.它被构造,存储在临时变量temp中.该表的下一个值为nil.它获得值“d”.结果存储在局部变量头中.
所以现在head有值table-d.下一步:
head = {next = head, value = "c"}
一样:
do
local temp = {}
temp.next = head --Not nil anymore.
temp.value = "c"
head = temp
end
好的,我们创建一个新表.为清楚起见,我们将此表格称为c表.
我们将它存储在temp中.然后我们将它的下一个字段设置为head中的值.该值是表-d.我们将值字段设置为“c”.然后将table-c存入head.
table-c表如下所示:
{
next = { value = "d" }
value = "c"
}
那是存储在头部的表.
这继续这样.那么什么东西会被“覆盖”?
