Originally Posted by Riraito
ok so I tried doing it manually and it seemed to work fine, but when I ran it in my code, it still acts like Im doing a simple a = b; statement, and when I change one table, it changes the other
|
a = b doesn't make a copy, it makes a reference. Changing one will change the other.
Depending on what you want to do, tekkub's answer may be workable for you:
b = setmetatable({}, {__index = a})
Alternatively you can copy all of the keys in a for loop. If you just want to copy raw data, however, the quickest solution, for a simple table, will be to use a metatable to reference it until it's changed. For more complicated solutions (specifically handling nested tables), try this code I just made up now (very minimally tested!)....
Code:
-- Generates the metamethod to handle copying data
function _GenMetamethod(table)
return function(t, k)
if not rawget(t, k) then
local v = table[k];
if not v then return nil; end
if type(v) == "table" then
local newval = {};
setmetatable(newval, {__index = _GenMetamethod(v)});
return newval;
else
rawset(t, k, v);
return v;
end
else
return rawget(t, k);
end
end
end
-- Now we have a table
a = {1,2,3,4,5};
-- We can copy it to b like this
b = {};
setmetatable(b, {__index = _GenMetamethod(a)});
-- Now let's try this...
b[2] = 10;
assert(a[2] == 2 and b[2] == 10);
assert(a[3] == 3 and b[3] == 3);
If you don't understand how or why this works, I recommend checking out Programmign in Lua (PiL) regarding metatables