Связанный список должен иметь способ добраться до следующего значения в цепочке.
Без определения 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