Can you copy an object?

Hello,

I wanted to ask whether it is possible to copy objects.

obj = class()
obj2 = obj
This only creates a reference, meaning that obj2.attribute = 10 would also change obj.attribute to 10. However, I’d like to have obj2 to be independent from obj. Is this possible?

Thanks in advance for any help!

@Leon Instead of copying a class, just make a new instance of it.

If you have obj1=class(), then create an instance of it. A=obj1. Then you can create another instance(copy) B=obj1. Or are you trying to create a copy of A after you updated a bunch of variables in A. If that’s the case, then you need to copy each variable of A to B. This is the same thing with tables. If you have a table named T1, then if you say T2=T1, then anything you change in T2 changes in T1. For the tables to be separate, you need a for loop to copy T2[xx]=T1[xx].

What I meant was this (e.g.):

A = class()
A.x = 10
B = A
B.x = 20
print(A.20)

This returns 20, which means that B is just a reference to A (–> changes to B affect A).

So if I understand you correctly, it is impossible to easily “copy” an object but I would have to set all variables separately?

@Leon As far as I know, yes, you have to copy each individual variable from one class to the other. There may be an easy way to copy each one, but I’ve never needed to, so at this point I’m not sure. I’ll play around and see if I can find something.

PS. I found this, try using json.encode and json.decode

@Leon Heres an example of copying a class and changing value without affecting the original.

PS. It looks like the json encode only copies the variables in :init. If there are other functions that use other self.variables, those don’t seem to get copies.

displayMode(STANDARD)

function setup()
    a1=xx(10,20,30,40)   
    str=json.encode(a1)
    a2=json.decode(str)
    print("a1",a1.a,a1.b,a1.x,a1.y)  
    print("a2",a2.a,a2.b,a2.x,a2.y)
    a2.a=111  
    a2.b=222
    print("a1",a1.a,a1.b,a1.x,a1.y)  
    print("a2",a2.a,a2.b,a2.x,a2.y)
end

xx = class()

function xx:init(a,b,x,y)
    self.a=a
    self.b=b
    self.x=x
    self.y=y
end

I’ve just tested your example. Seems to work perfectly. Thanks for your help :slight_smile:

You could use class inhertiance.

A = class()
in init: a = 20, b = 10

B = class(A)
in init: A.init(self), a = 10

→ A will initialize a with 20, B will init a with 10, both classes have b as 10

I use this routine to make a copy of a table:

function deepCopy(t)
    if type(t) ~= 'table' then return t end
    local mt = getmetatable(t)
    local res = {}
    for k,v in pairs(t) do
        if type(v) == 'table' then
            v = deepCopy(v)
        end
        res[k] = v
    end
    setmetatable(res,mt)
    return res
end