A simple question about copying objects

Hi all,

I’m new to Codea and also to Lua. I have what is probably a basic programming question:

Suppose I create an instance of a class, and then I change one of its properties.

widget = Widget()
widget.propertyA = 99

How can I copy this object into a new instance that is identical to the first? If I do this:

secondWidget = widget

It of course gives me two variables pointing at the same object.

secondWidget.propertyA = 10 – this means that widget.propertyA now also equals 10.

Is there a simple way to copy an object into a new instance, or do I have to create my own method for this?


You have to create your own method:

function MyClass:copy()
    local obj = MyClass()
    obj.x = self.x
    obj.y = self.y
    ... -- and so on
    return obj