How does this Lua Linked List example actually work?

After a few years I’ve been redesigning programming, and now I am focused on C # and Lua. The book I'm using for Lua has an example for a linked list, but it's hard for me to understand how this works.

list = nil for line in io.lines() do list = {next = list, value = line} end 

If I read it right

  • he creates a new table
  • Assigning a list to this table, setting the β€œnext” key / identifier (correct terminology?) to point to the list (which is still zero at the point of the first created table).
  • then set the key / identifier "value" for what was read in
  • then the "list" now actually points to the newly created table

Then at the next run of the cycle

  • create the following table
  • setting the "next" key / identifier to indicate a list (which now points to a previously created table)
  • then set the key / identifier "value" for what was read in
  • then the list now actually points to the newly created table ... again

I just wanted to be sure that I understood exactly how this worked, because it seemed a little strange / strange that this list was trying to create a table and indicate that it was currently pointing just before the completion of the row and the list was updated to point to the newly created table.

Or am I here from here?

+4
source share
2 answers

This is somewhat similar to the fact that LIFO-linked lists are in other languages ​​(e.g. c or ). Yes, you followed him correctly.

Suppose my inputs are: (in the same order)

  • 21
  • Hello
  • 35
  • No

Then my list is created as:

 list = { value = "No", next = { value = 35, next = { value = "Hi", next = { value = 21 next = nil } } } } 
+4
source

Essentially, what happens is that inside the for loop you create a table, and the next key is nil, initially. In subsequent cycles, you create the table again, and using the list variable, you assign it next key, which is now a link to the previous table, and so on.

I will give you an example.

 list = nil -- this is optional for i=1,3 do list = {val=i, next=list} end print(list.val) 

If you were to print(list.val) or print(list.next.val) they would print different values. I know it kind of baffled me when I first saw it.

0
source

All Articles