Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Can you copy an object?

in Questions Posts: 117


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!


  • dave1707dave1707 Mod
    Posts: 8,505

    @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].

  • Posts: 117

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

    A = class()
    A.x = 10
    B = A
    B.x = 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?

  • dave1707dave1707 Mod
    edited January 10 Posts: 8,505

    @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

  • dave1707dave1707 Mod
    edited January 10 Posts: 8,505

    @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.

    function setup()
    xx = class()
    function xx:init(a,b,x,y)
  • Posts: 117

    I've just tested your example. Seems to work perfectly. Thanks for your help :)

  • AnatolyAnatoly Mod
    Posts: 889

    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

  • edited January 13 Posts: 545

    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)
            res[k] = v
        return res
Sign In or Register to comment.