lua - 使用 Lua 中的函数修改链表

标签 lua scripting linked-list pico-8

我的问题是关于以下代码片段:

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/

相关文章:

c++ - 程序收到信号 SIGSEGV,段错误。 C++ 列表

c - 快速制作静态链表

c++ - 跟踪 Lua 中的变量以读取访问权限以启动用户定义的 C++ 方法/函数

c - Lua c lib Windows : The specified procedure could not be found

nginx - 命中 url 时找不到 404 页面,但从索引页面上的链接打开时正确提供

database - 将数据从一个 Informix 数据库复制到另一个数据库的脚本

function - Lua - 检查用户输入的表是否存在并从中读取

linux - Shell 脚本支持——不同 URL 上的多个 nslookups

php - 您如何使用脚本语言(PHP、Python 等)来提高您的生产力?

c - c中如何比较栈和链表的元素?