Howdy, Stranger!

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

[SugarCube 2.9.0] Cloning an object and all sub-objects, and a question about the Set macro.

Hello,
I'm looking to clone an object and all of its sub-objects (and their properties) into a new object with a different name, but I didn't see a way of doing this in SugarCube 2's documentation. I saw quite a few methods of doing this through JavaScript/jQuery on stackoverflow, but I'm not familiar enough with JS to know which method would be 'proper' in this situation.

Side question:
I noticed that you can group variable assignments and object creation with the Set macro, like so:

Individually:
<<set $foo to {}>>
<<set $foo.bar to {}>>
<<set $foo.bar.foobar to {}>>
...

Grouped:
<<set $foo to {},
$foo.bar to {},
$foo.bar.foobar to {},
...
>>

Is there any benefit to doing it one way over the other?

Thank you for your time.

Comments

  • Kokonoe wrote: »
    I'm looking to clone an object and all of its sub-objects (and their properties) into a new object with a different name, but I didn't see a way of doing this in SugarCube 2's documentation.
    If you need a deep copy of the object in question, then you'll probably want to use SugarCube's built-in clone() function (currently undocumented). For example:
    /* clone(original) → copy */
    <<set $fooCopy to clone($foo)>>
    

    Kokonoe wrote: »
    I noticed that you can group variable assignments and object creation with the Set macro, like so:

    […]

    Is there any benefit to doing it one way over the other?
    Not really, no. Your latter example has the very minor benefit of only invoking the <<set>> macro once.

    Additionally, you could also do the following:
    <<set $foo to {
    	bar : {
    		foobar : {
    		}
    	},
    	baz : {
    		foobaz : {
    		}
    	}
    }>>
    
    Which is on par with your latter example.

    In the end, use whichever of those you feel most comfortable with.
  • If you need a deep copy of the object in question, then you'll probably want to use SugarCube's built-in clone() function (currently undocumented). For example:
    /* clone(original) → copy */
    <<set $fooCopy to clone($foo)>>
    

    Kokonoe wrote: »
    I noticed that you can group variable assignments and object creation with the Set macro, like so:

    […]

    Is there any benefit to doing it one way over the other?

    Not really, no. Your latter example has the very minor benefit of only invoking the <<set>> macro once.

    Additionally, you could also do the following:

    […]

    Which is on par with your latter example.

    In the end, use whichever of those you feel most comfortable with.

    Fantastic! Thank you very much.
  • Cool! That clone function is going to come in handy for my game too.
Sign In or Register to comment.