Reputation: 67
I have been learning about table constructors in Lua from http://www.lua.org/pil/3.6.html and I can't understand the difference between these two pieces of code.
--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
Upvotes: 2
Views: 81
Reputation: 5564
The for loop of your code does not preserve the previous value of list
. list
will end up containing the last line from the input. Your while loop will be infinite.
The for loop of their code saves the previous value of list
inside the new list
value. Their while loop changes l
on each iteration. As a result, it prints a different value each time, and it stops when l
is nil
.
Upvotes: 2
Reputation: 5021
A linked list needs to have a way to get to the next value in the chain.
Without defining next
in the table you have no next value, indexing value
does not automatically move l
to the next value in the list. By not defining next = list
the last value of list
is lost and your end result will be only a single value, the last value from your data source.
I changed this example so that is didn't need a file to work with:
Here your code will loop indefinitely printing f each and every time.
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
Where as the code from the example will go through each value given and complete.
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
Upvotes: 2