[Twine 2.1.3/ SugarCube 2.18.0] Problem with saves and arrays?

0 votes
asked Jul 4, 2017 by GloomDoom (470 points)

 Hello. I have a problem. If you execute code below it will work, but if you save and then load you will see that $EXTERNAL[$INTERNAL[0]] - undefined. I don't understand why. Is this bug or i need to know something about saves? I was working on a game in a month and it has many constructions like this. Need I to start again or it can be fixed with macros or something else?

::StoryInit
<<set $INTERNAL = []>>
<<set $INTERNAL[0] = "Zero">>
<<set $EXTERNAL = []>>
<<set $EXTERNAL[$INTERNAL[0]] = "External">>

::Start
EXTERNAL = <<print $EXTERNAL[$INTERNAL[0]]>>

 

1 Answer

0 votes
answered Jul 4, 2017 by greyelf (58,490 points)
selected Jul 5, 2017 by GloomDoom
 
Best answer

Your example code may not be doing what you think it is, due to Array indexes being number based (starting with 0).

a. The $INTERNAL[0] = "Zero" line is adding a String value of "Zero" as the first item of the Array object contained within the $INTERNAL variable.

b. The $EXTERNAL[$INTERNAL[0]] = "External" line is adding an Object Member Property named "Zero" to the Array object contained within the $EXTERNAL variable, then assign a String value of "External" to that new object property.
warning: This practice may lead to issues if the Reader saves then re-load that save, due to the new property not correct being recreated during the load process.

 

re: Adding elements to an (Standard) Array.
I generally suggest using the <Array>.push() method to add items to an Array, as it stops the issue described in point B from occurring.

<<set $INTERNAL to []>>
<<set $INTERNAL.push("Zero")>>

 

re: Adding key based elements to a Collection:
1. Using a generic Object to store the key/value pairs:

<<set $EXTERNAL to {}>>
<<set $EXTERNAL[$INTERNAL[0]] to "External">>

2. Using a Javascript Map object to store the key/value pairs.

<<set $MAP to new Map()>>
<<set $MAP.set($INTERNAL[0], "External")>>

 

The TwineScript to access the elements would look like the following:

EXTERNAL = <<print $EXTERNAL[$INTERNAL[0]]>>

MAP = <<print $MAP.get($INTERNAL[0])>>

 

asked Jul 5, 2017 by GloomDoom (470 points)
edited Jul 5, 2017 by GloomDoom
[Twine 2.1.3/ Sugarcube 2.18.0] How to use arrays without push()?
Welcome to Twine Q&A, where you can ask questions and receive answers from other members of the community.

You can also find hints and information on Twine on the official wiki and the old forums archive.

See a spam question? Flag it instead of downvoting. A question flagged enough times will automatically be hidden while moderators review it.
...