I am trying to get a handle on how objects work in Codea. I was surprised by the output of the following code snippet. Thing is a class with a single member variable called self.x.
bob = Thing()
bob.x = 12
dave = bob
dave.x = 7
print("Dave's x-value: " .. dave.x) -- Outputs 7
print("Bob's x-value: " .. bob.x) -- Also outputs 7
So it seems that dave is a reference to bob, not a stand-alone instance of the Thing class.
Is there a way to create a copy of an object that is not a reference? Do I need to implement a copy constructor, and if so, how do I do that in Codea?
Thing = class()
function Thing:init( objToCopy )
if objToCopy ~= nil then
self.x = objToCopy.x
end
end
```
Using it:
bob = Thing()
bob.x = 12
dave = Thing(bob)
dave.x = 7
```
That simulates a "copy constructor". However I would suggest having a specific copy method, as it's easier to reason about the calling code and leaves the init method for construction only.
Thing = class()
function Thing:init(x, y)
-- Normal constructor
self.x = x
self.y = y
end
function Thing:copy()
local copyOfThing = Thing()
-- Copy fields from self...
copyOfThing.x = self.x
copyOfThing.y = self.y
return copyOfThing
end
```
Using it:
bob = Thing()
bob.x = 12
dave = bob:copy()
dave.x = 7
```
Thanks for the response, and I take your point about having a designated copy function. I think I’ve got this working now (both in the silly bob/dave example and in the real stuff I’m working on).