Howdy, Stranger!

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

Quick question about Objects/Nevermind! Solved it!

Can you set an object equal to an object? For example, if I set $player = $Dragon, would that mean that $player.HP equals $Dragon.HP or would I have to set it manually?

Edit: I feel bad because almost as soon as I posted this, I figured out a way to check if you can set an object equal to an object. The answer is yes. I'm pretty sure it only works if the two objects have the same properties, but it works. I'll leave this here if anyone else was wondering that.

Comments

  • Your example of set $player = $Dragon results in both of the two variables ($player and $Dragon) pointing to the same object.

    This is because the first variable ($Dragon) contained whats know as an object reference (basically the location in memory the object is being stored), and it was the object reference that you copied into the second variable ($player) and this is why they are the same.

    // This can be seen by first creating the object and assigning it to the $Dragon variable.
    <<set $Dragon = {name: "Dragon", HP: 20}>>

    // Create the $player variable, assigning it a reference to the same object that $Dragoon does.
    <<set $player = $Dragon>>

    // Check the players HP, it will be 20
    <<print $player.HP>>

    // Change the Dragons HP to 100.
    <<set $Dragon.HP = 100>>

    // See that that the players HP has also changed to 100
    <<print $player.HP>>
  • Caveat!

    Depending on what you're looking for, that may not work correctly beyond the initial passage where you do it, since most (all?) Twine headers clone the $variable store between turns.  Meaning that on the turn after you do the assignment, $player and $Dragon will go from referencing the same object to referencing equivalent cloned objects (copies of the original object).


    So, if you wanted $player to be a copy of $Dragon, then that will probably work fine as-is (as long as you don't modify it until after a turn has passed and it's been made into a copy that is).  If you need to modify it immediately after assignment, and thus need it to become a copy upon assignment, then use the clone() function, like so:

    <<set $player to clone($Dragon)>>

    On the other hand, if you actually need to be able to consistently reference the same object (well, its descendant clones), then that will not work as expected.  The usual solution is to store the objects you wish to reference within another object and then pass forward the name of the sub-object you wish to reference.  For example:

    <<set $npc to {
    dragon: { name: "Dragon", hp: 20 }
    }>>

    <<set $who to "dragon">>

    <<print "The " + $npc[$who].name + " has " + $npc[$who].hp + " hit points left.">>

    <<set $npc[$who].hp -= 5>>

    <<print "The " + $npc[$who].name + " has " + $npc[$who].hp + " hit points left.">>
Sign In or Register to comment.