我从http://www.lua.org/pil/3.6.html开始学习Lua中的表构造函数,我无法理解这两段代码之间的区别。
--between code I've written--
list = nil
for line in io.lines() do
list = {value=line}
end
l = list
while l do
print(l.value)
end
--and between code they have written--
list = nil
for line in io.lines() do
list = {next=list, value=line}
end
l = list
while l do
print(l.value)
l = l.next
end
链接列表需要一种方法来获得链中的下一个值。
在表中没有定义next
的情况下您没有下一个值,索引value
不会自动将l
移动到列表中的下一个值。如果不定义next = list
,则list
的最后一个值将丢失,并且最终结果将仅为单个值,即数据源中的最后一个值。
我更改了此示例,因此不需要使用文件:
这里您的代码每次都会无限循环地循环打印f。
list = nil
for _,letter in ipairs({'a','b','c','d','e','f'}) do
list = {value=letter} -- we reassign list with new data without preserving the
-- previous data
end
l = list
while l do
print(l.value) -- the last value of list was {value = 'f'} and it will not
-- change in this loop
end
示例中的代码将遍历每个给定的值并完成。
list = nil -- this marks the end of the list and creates our name
-- we will use to store the list.
for _,letter in ipairs({'a','b','c','d','e','f'}) do
list = {next=list, value=letter} -- the first loop we will create a table where `next` is
-- nil.
-- on the second loop we create a table where `next` is
-- referencing the table from loop 1 that is stored in list.
-- this will repeat until we have gone through all the
-- letter from our source.
end
l = list
while l do
print(l.value) -- print our letter.
l = l.next -- move on to the table we stored in `next`.
-- this loop ends when we get to the value where
-- `next` was nil.
-- the table from the first loop of our for loop.
end
您的代码的for循环不会保留list
的先前值。 list
将最终包含输入的最后一行。您的while循环将是无限的。
其代码的for循环将list
的先前值保存在新的list
值内。他们的while循环在每次迭代中都会更改l
。结果,它每次打印一个不同的值,并且当l
为nil
时停止。