How do you make a deep copy of a custom class?

Example is this “a” class.

local a = {};

a.new = function(b)
	local s = {};
	s.b = b;
	return setmetatable(s, {__index = a})
end

function a:c()
	print(self.b)
end

return a;

Then we have this; How will I make a clone method that makes a deep copy of the object with the class? So that this can work.

local e = a.new(3)

local deepcopy = e:clone()
deepcopy:c() -- 3
1 Like

First off, your example wouldn’t work even without a copy. a:c prints self.b, not return it. The print function does not return anything.
Here’s something you could do, though:

function a:Clone()
    local new = {}
    for key, value in pairs(self) do
        new[key] = value
    end
    setmetatable(new, getmetatable(self))
    return new
end

That makes a shallow copy, not a deep copy (only the first “layer” of keys/values are copied, and the value will still point to the same references from the values of the old table)

http://lua-users.org/wiki/CopyTable

4 Likes

My mistake, I thought your issue lied with the metatables.