Thread Tools Display Modes
Prev Previous Post   Next Post Next
06/17/14, 06:51 AM   #1
zgrssd
AddOn Author - Click to view addons
Join Date: May 2014
Posts: 280
Clone vs Copy - any libs for that?

I ran into the small issues that tables are generally handed to and from function by reference instead of by value. So I need to channel my inner mad scientist and start cloning.

Some search gave me these code for shallow and deep cloning respectively:
Code:
function copy (t) -- shallow-copy a table
    if type(t) ~= "table" then return t end
    local meta = getmetatable(t)
    local target = {}
    for k, v in pairs(t) do target[k] = v end
    setmetatable(target, meta)
    return target
end
Code:
function clone (t) -- deep-copy a table
    if type(t) ~= "table" then return t end
    local meta = getmetatable(t)
    local target = {}
    for k, v in pairs(t) do
        if type(v) == "table" then
            target[k] = clone(v)
        else
            target[k] = v
        end
    end
    setmetatable(target, meta)
    return target
end
Now I don't understand enough about metatables, tables and lua in general to be certain if that is code right (it looks like it).
And of course it could help to fold both functions into one with a bool switch/int to tell the maximum depth to clone.

Has annybody already written some code for cloning in his library so I don't repeat the same code?
  Reply With Quote
 

ESOUI » Developer Discussions » General Authoring Discussion » Clone vs Copy - any libs for that?


Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off