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