[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: copy a table
- From: manel <lista@...>
- Date: Mon, 29 Jan 2007 11:49:45 +0100 (CET)
On Mon, 29 Jan 2007, Thomas Hafner wrote:
Hello,
what's the easiest way to copy a given table?
If variable ``source'' references the table, just the assignment
target = source
won't do it: no new table will be constructed, but ``target'' will
reference the same table as ``source'' (e.g. after the assignment
target[1]=42, source[1] will be set to 42, too).
Regards
Thomas
Hello Thomas
There is no simple way of copying a table in the most general case
(because tables can self-reference). A simple one (which does not
treat well self-references) is:
function tablecopy (t)
local tc = {}
if type(t) == "table" then
for k, v in pairs(t) do
tc[k] = tablecopy(v)
end
else
return t
end
return tc
end
-- example
t = {c = "a", "b", {1, 2, 3}}
tc = tablecopy(t)
But you could take a look at http://lua-users.org/wiki/CopyTable,
much better.
Manel