Howdy, Stranger!

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

How do I copy an object properly in sugarcube?

Essentially, I want to achieve something like this:
<<set $activePerson to { name : "David" }>>
<<set $secondPerson to $activePerson>>
<<set $activePerson.name to "Jane">>
<<print $secondPerson.name>>
where the print statement prints "David" and not "Jane".
However, it is my understanding that until the passage exits, the variable "secondPerson" is treated as a reference to "activePerson" instead of its own object, which leads me to believe that I'm doing it wrong.
So how do I copy an object properly within a single passage?

Comments

  • edited April 2016
    The best way would be to use the same function that SugarCube itself uses to make copies of any objects within the variable store from turn to turn, clone(). The clone() function makes a deep copy of the object in question (i.e. even sub-objects are cloned).

    For example:
    <<set $activePerson to { name : "David" }>>
    <<set $secondPerson to clone($activePerson)>>
    <<set $activePerson.name to "Jane">>
    
    <<print $activePerson.name>>  → Prints: Jane
    <<print $secondPerson.name>>  → Prints: David
    
  • edited April 2016
    edit: my post was similar to TheMadExile's but he beat me to it.

    @TheMadExile
    Is that function documented?
  • Thanks a lot. This is perfect - especially the part about sub-objects.
  • greyelf wrote: »
    Is that function documented?
    It is not, no. I'm honestly unsure what category I'd place it under. In most cases there should not be a lot of author demand for system-level internal utility functions. I am, in general, also leery of documenting APIs that there is no pressing need to document—doing so effectively makes them part of the public APIs and then I'm stuck with them, and there's already too much legacy cruft hanging around for my tastes.

    Still, in this case, the clone() API has been stable for a very long time and is extremely unlikely to change in the future, so having it documented shouldn't be an issue—still have to decide where to put it though.
Sign In or Register to comment.