Help please: proper way to COPY a table

I think I know what is happening, just not how to get the results I want instead.

Here’s some stripped down sample code:

  
a = {1,2}  
  
print(table.concat(a,",")) --\>\> 1,2  
  
b = a  
  
print(table.concat(b,",")) --\>\>1,2  
  
b[1] = 3  
  
print(table.concat(b,",")) --\>\>3,2  
  
print(table.concat(a,","))--\>\>3,2  
  

So I (now) get that when I create “b”, it actually a reference to a, so that when I change b, I change a as well. What I want to do is create a new table “b”, with the same values of table “a”, but after the creation I want to manipulate them independent of each other. So in the above sample, “a” would stay “1,2” and only “b” would become “3,2”.

I know this is a simple fix, but I admit, I’m stumped. [import]uid: 64596 topic_id: 19217 reply_id: 319217[/import]

Have you tried something like:

[code]

a = {1,2}
b = {}

for i = 1, #a do
b[i] = a[i]
end

[/code] [import]uid: 23649 topic_id: 19217 reply_id: 74136[/import]

Jeremy’s fix works for simple tables that do not contain other tables and is more optimal for such. In case your table could hold another table here’s my deep copy function, it assumes that the input (t) is a table, and iterates through each key(k)/value(v) pair in the table using recursion when it finds that the value is another table.

function DeepCopy(t)  
 local new\_table = {}  
 for k,v in pairs(t) do  
 if type(v) == "table" then  
 new\_table[k] = DeepCopy(v)  
 else  
 new\_table[k] = v  
 end  
 end  
 return new\_table  
end  

Usage:

local a = {1, {2,3}, 4} local b = DeepCopy(a) [import]uid: 100558 topic_id: 19217 reply_id: 74196[/import]

What Licensing proposed is completely valid, however keep in mind that this can [and if you try to use this deep copy on lua “objects” will most probably will] end up with stack overflow.
I have used this code for debugging purposes and I used it for one of my “objects” and ti ended up with a small disaster ;] [import]uid: 109453 topic_id: 19217 reply_id: 74211[/import]

About the only reason to get stack overflow from that function is passing it an extremely deep table or a table that contains a a circular reference somewhere in its structure. One noted case is that most Corona display objects seem to cause issues with this kind of table iteration. [import]uid: 100558 topic_id: 19217 reply_id: 74240[/import]