如何按值复制 Lua 表? [英] How do you copy a Lua table by value?

查看:28
本文介绍了如何按值复制 Lua 表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我写了一些 Lua 代码,例如:

Recently I wrote a bit of Lua code something like:

local a = {}
for i = 1, n do
   local copy = a
   -- alter the values in the copy
end

显然,这不是我想要做的,因为变量保存对匿名表的引用,而不是 Lua 中表本身的值.这在 Lua 编程 中有明确规定,但我忘记了.

Obviously, that wasn't what I wanted to do since variables hold references to an anonymous table not the values of the table themselves in Lua. This is clearly laid out in Programming in Lua, but I'd forgotten about it.

所以问题是我应该写什么而不是 copy = a 来获取 a 中值的副本?

So the question is what should I write instead of copy = a to get a copy of the values in a?

推荐答案

为了玩一点可读性的代码高尔夫,这里有一个处理标准棘手案例的简短版本:

To play a little readable-code-golf, here's a short version that handles the standard tricky cases:

  • 表作为键,
  • 保留元表,以及
  • 递归表.

我们可以用 7 行代码来完成:

We can do this in 7 lines:

function copy(obj, seen)
  if type(obj) ~= 'table' then return obj end
  if seen and seen[obj] then return seen[obj] end
  local s = seen or {}
  local res = setmetatable({}, getmetatable(obj))
  s[obj] = res
  for k, v in pairs(obj) do res[copy(k, s)] = copy(v, s) end
  return res
end

这个要点中有一段关于 Lua 深拷贝操作的简短描述.

There is a short write-up of Lua deep-copy operations in this gist.

另一个有用的参考是这个 Lua-users wiki 页面,其中包含一个关于如何避免 __pairs 元方法.

Another useful reference is this Lua-users wiki page, which includes an example on how to avoid the __pairs metamethod.

这篇关于如何按值复制 Lua 表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆