Page 1 of 1

How do I clone a table

Posted: Wed Aug 06, 2014 11:26 pm
by Ranguna259
I'd like to know a way to clone tables.
Whenver I try to do

Code: Select all

table2=table1
and change data inside table 2, that same data will change in table1.

I've thought of using serialization libs to serialize a table and then load the string into the new table but mayber there's another way ..?

Re: How do I clone a table

Posted: Thu Aug 07, 2014 12:24 am
by jangsy5

Code: Select all

a = {1,2,3}
b = {}

for k, v in ipairs(a) do
    b[k] = v
end
Pretty much means instead of b referring to a, b has a table that refers to the same values as a. Which is kind of cloning right? Well this is the best I can think of. You have to note that it'll reference values that are tables so you need to clone those too, probably using if statement to check.

Re: How do I clone a table

Posted: Thu Aug 07, 2014 12:43 am
by davisdude
*Made by Robin

Code: Select all

function DeepCopy( Table, Cache ) -- Makes a deep copy of a table. 
    if type( Table ) ~= 'table' then
        return Table
    end

    Cache = Cache or {}
    if Cache[Table] then
        return Cache[Table]
    end

    local New = {}
    Cache[Table] = New
    for Key, Value in pairs( Table ) do
        New[DeepCopy( Key, Cache)] = DeepCopy( Value, Cache )
    end

    return New
end

Re: How do I clone a table

Posted: Thu Aug 07, 2014 1:24 am
by Ranguna259
jangsy5 wrote:You have to note that it'll reference values that are tables so you need to clone those too, probably using if statement to check.
I'd already thought of that but, as you said, tables within tables are the problem and if checks would not be the solution, but apparently Robin found a way.(or someone else did because I think I've seen his solution somewhere else)
davisdude wrote:*Made by Robin

Code: Select all

function DeepCopy( Table, Cache ) -- Makes a deep copy of a table. 
    if type( Table ) ~= 'table' then
        return Table
    end

    Cache = Cache or {}
    if Cache[Table] then
        return Cache[Table]
    end

    local New = {}
    Cache[Table] = New
    for Key, Value in pairs( Table ) do
        New[DeepCopy( Key, Cache)] = DeepCopy( Value, Cache )
    end

    return New
end
Thank you very much for sharing, and thank you Robin for coding this :)