Search code examples
luascriptinglinked-listpico-8

Modifying a Linked List With a Function in Lua


My question is regarding the below code snippet:

function add_node(list, v)
 list={next=list, val=v}
end

function print_linked_list(list)
 local l=list
 while l do
  print(l.val)
  l=l.next
 end
end

root=nil
root={next=root, val=0}
add_node(root, 1)
--root={next=root, val=2}
print_linked_list(root)

If I do the operation through the currently commented "root={nxt=root, val=1}" it works as expected. The print function will traverse the list and print both values. If I add a new node through the add_node function at the top of the script, which has essentially the same code in it, it'll only print the first created node.

Why is it that putting the operation in a function does not properly modify the list? The only thing I can think of is that the node created in add_node(list, v) is local only.

Finally, how can I get around this while keeping the code readable?


Solution

  • The only thing I can think of is that the node created in add_node(list, v) is local only.

    That's correct. Function parameters are implicitly local. All you need to do is return the value instead of assigning it:

    function add_node(list, v)
      return {next=list, val=v}
    end
    

    And later:

    root = add_node(root, 1)