Related Lua Lists

I recently looked at linked lists in Lua and asked a quick question that so far I have not been able to find an answer for

local head = nil head = {next = head, value = "d"} head = {next = head, value = "c"} head = {next = head, value = "b"} head = {next = head, value = "a"} local entry = head while entry do print(entry.value) entry = entry.next end 

This will print out "a, b, c, d". I understand why it will print back, since the first available <node 'will be the last created (with value = a). My question is why the “head” created before the final one still exists and is not just overwritten in memory.

+4
source share
1 answer

What do you mean by "rewriting in memory"? Nothing that you do will make it happen.

See what you do step by step.

 local head = nil 

Now there is a local variable called head . It matters nil .

 head = {next = head, value = "d"} 

Let me break this down into the flow of operations here. This is equivalent to the following:

 do local temp = {} temp.next = head --This is still `nil` temp.value = "d" head = temp end 

Each table you create is a unique value. So call this first table table-d . It is designed, stored in the temp temporary variable. The table is assigned the value next nil . And it gets the value "d" . And the result is stored in the local variable head .

So now head has the value table-d . Next step:

 head = {next = head, value = "c"} 

Same:

 do local temp = {} temp.next = head --Not nil anymore. temp.value = "c" head = temp end 

OK, we are creating a new table. For clarity, we will call this table table-c .

Save this in temp . Then we set the next value for this field to head . This is the value of table-d . We set the value field to "c" . And then save table-c to head .

Table table-c looks like this:

 { next = { value = "d" } value = "c" } 

This is a table stored in head .

This continues as follows. So where would something be “rewritten”?

+6
source

Source: https://habr.com/ru/post/1495404/


All Articles