0 votes
by (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?

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



1 Answer

0 votes
by (157k points)
selected by
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:


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


asked Jul 5, 2017 by (470 points)
edited Jul 5, 2017 by
[Twine 2.1.3/ Sugarcube 2.18.0] How to use arrays without push()?

