这两个代码在Lua中有什么区别

问题描述 投票:1回答:2

我从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
constructor lua linked-list
2个回答
0
投票

链接列表需要一种方法来获得链中的下一个值。

在表中没有定义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

0
投票

您的代码的for循环不会保留list的先前值。 list将最终包含输入的最后一行。您的while循环将是无限的。

其代码的for循环将list的先前值保存在新的list值内。他们的while循环在每次迭代中都会更改l。结果,它每次打印一个不同的值,并且当lnil时停止。

© www.soinside.com 2019 - 2024. All rights reserved.