JSicking84
JSicking84

Reputation: 55

How does this Linked List example in Lua actually work?

I'm in the process of relearning programming after several years and I'm currently focusing on both C# and Lua. The book I'm using for Lua has an example for a Linked List, but I'm having a difficult time understanding exactly how it's working.

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

If i'm reading this right

Then on the next run through of the loop

I just wanted to be sure I understood exactly how this was working as it seemed a little odd/weird that the list was trying was creating a table and pointing to whatever it was currently pointing to just before the execution of the line completed and the list was updated to point at the newest created table.

Or am I way off here?

Upvotes: 4

Views: 3137

Answers (2)

rumpled105
rumpled105

Reputation: 27

Essentially what is happening is, inside a for loop, you are creating a table and the next key is nil, initially. In subsequent loops, you are creating a table again and with the list variable you assign it to the next key, which is now a reference to the previous table, and so on.

I'll give you an example.

for i=1,3 do
    list = {int=i, next=list}
end

When this executes, the first next key will be nil because list hasn't been defined yet. But in the next table its next key will be a reference to the previous table, and so on. If you try to print list.int and list.next, they would be referring to the table where int=3 because the for loop ends at 3 and thus the variable refers to that part. If you need to change this, you simply change the numeric for loop to something like

for i=3,1,-1 do

So it would actually look like this:

list = {int=1, next=nil}
list = {int=2, next=previousTable}
list = {int=3, next=previousTable}

or

list = {
    int=3, 
    next = {
        int=2, 
        next = {
            int=1, 
            next=nil
        }
    }
}

Hope this helps.

Upvotes: 0

hjpotter92
hjpotter92

Reputation: 80649

This is somewhat similar to what LIFO linked lists are in other languages(like or ). Yes, you were following it correctly.

Suppose my inputs are:(in the same order)

  • 21
  • Hi
  • 35
  • No

Then, my list is created as:

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

Upvotes: 4

Related Questions