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?