如何按值复制Lua表? [英] How do you copy a Lua table by value?
问题描述
最近我写了一些Lua代码,例如:
local a = {}
for i = 1, n do
local copy = a
-- alter the values in the copy
end
显然,那不是我想要做的,因为变量持有对匿名表的引用,而不是Lua中表本身的值. 在Lua中编程中清楚地列出了这一点,但我忘记了. /p>
所以问题是我应该写什么而不是copy = a
来获取a
中值的副本?
要播放一些可读的代码高尔夫,以下是处理标准棘手情况的简短版本:
- 表作为键,
- 保留元表,和
- 递归表.
我们可以在7行中完成此操作:
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深度复制操作文章.
另一个有用的参考是 Lua-users Wiki页面,其中包含有关如何避免__pairs
的示例元方法.
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
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.
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:
- tables as keys,
- preserving metatables, and
- recursive tables.
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
There is a short write-up of Lua deep-copy operations in this gist.
Another useful reference is this Lua-users wiki page, which includes an example on how to avoid the __pairs
metamethod.
这篇关于如何按值复制Lua表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!