Here is what I actually did:
for j,x in ipairs(a) do copy[j] = x end
As Doub mentions , if your tables are not strictly monotonously growing, this should be pairs not ipairs .
I also found a deepcopy function that is more robust:
function deepcopy(orig) local orig_type = type(orig) local copy if orig_type == 'table' then copy = {} for orig_key, orig_value in next, orig, nil do copy[deepcopy(orig_key)] = deepcopy(orig_value) end setmetatable(copy, deepcopy(getmetatable(orig))) else -- number, string, boolean, etc copy = orig end return copy end
It processes tables and meta tags, invoking itself recursively ( which is its own reward ). One of the smart bits is that you can pass it any value (regardless of the table or not), and it will be copied correctly. However, the cost is that it can potentially overflow the stack. Therefore, an even more robust (non-recursive) function may be required .
But this is an overflow for a very simple case when you want to copy an array to another variable.
Jon Ericson Mar 12 '09 at 21:52 2009-03-12 21:52
source share