Category: Advice

Replacing the Body of an Object Function

Suppose you have an object “a” that you have already instantiated members in.

a.b = 10

Now suppose you need to make the return of “a” equal to 9 so that:

print(a:)

… prints “9”. If you were to assign 9 to “a” directly, you would be giving “a” an entirely new object-function, thereby losing the member “b”. Fortunately, there is a way around the problem. Copper has a built-in function called “share_body” that allows two object-functions to share the same execution body. For example:

c = 9
share_body(c a)

… would allow “a” to have the body of “c”. If “c” gets destroyed from going out of scope, then “a” keeps the body. However, creating a new variable just to make a function body is unnecessary. If we create an ownerless object-function to share its body with “a”, then “a” will become the owner of the body.

share_body({9} a)

The ownerless object-function {9} is instantiated within the function-call parentheses of share_body where it dies but its body lives on. And there you have it, no copies required, no loss of object members.