使用 Lua 中的函数修改链表
Modifying a Linked List With a Function in Lua
我的问题是关于下面的代码片段:
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}" 进行操作,它会按预期工作。 print 函数将遍历列表并打印两个值。如果我通过脚本顶部的 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.
没错。函数参数是隐式局部的。您需要做的就是 return 值而不是分配它:
function add_node(list, v)
return {next=list, val=v}
end
以后:
root = add_node(root, 1)
我的问题是关于下面的代码片段:
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}" 进行操作,它会按预期工作。 print 函数将遍历列表并打印两个值。如果我通过脚本顶部的 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.
没错。函数参数是隐式局部的。您需要做的就是 return 值而不是分配它:
function add_node(list, v)
return {next=list, val=v}
end
以后:
root = add_node(root, 1)