我的问题是关于以下代码片段:
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)
如果我通过当前注释的“root={nxt=root, val=1}”执行操作,它会按预期工作。打印函数将遍历列表并打印这两个值。如果我通过脚本顶部的 add_node 函数添加一个新节点(其中的代码基本相同),它只会打印第一个创建的节点。
为什么将操作放在函数中并不能正确修改列表?我唯一能想到的是在 add_node(list, v) 中创建的节点只是本地的。
最后,如何在保持代码可读的同时解决这个问题?
最佳答案
The only thing I can think of is that the node created in add_node(list, v) is local only.
这是正确的。函数参数是隐式局部的。您需要做的就是返回值而不是分配它:
function add_node(list, v)
return {next=list, val=v}
end
之后:
root = add_node(root, 1)
关于lua - 使用 Lua 中的函数修改链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48814818/