Revision of How to use JavaScript arrays in Twine from Fri, 02/01/2013 - 06:11

An array is essentially an ordered list of data values, such as strings or number expressions. You can declare a Twine variable to be an array using just the set macro.

*To create an empty array called $inv: <<set $inv = [] >>
*To create an array called $inv containing the string "Dagger": <<set $inv = ["Dagger"] >>
*To create an array called $inv containing "Dagger", "Shield" and "Potion" in that order: <<set $inv = ["Dagger", "Shield", "Potion"] >>

To examine or change the values inside an array, a number of methods are available that can be used in the set, if and print macros. Here are some examples.

Examining arrays and their contents

*To print the entire contents of an array in order (usually for debug purposes): <<print $inv.toString() >>
*To see if the value "Magic Knife" is inside an array: <<if $inv.indexOf("Magic Knife") gte 0>>
*To get the number of values inside an array: <<set $size = $inv.length >>
*To get the first value inside an array: <<set $first = $inv[0] >>
*To get the last value inside an array: <<set $first = $inv[$inv.length - 1] >>

Changing values in arrays

*To add the value "Magic Knife" to the end of an array: <<set $inv.push("Magic Knife")>>
*To add the values "Blunt Axe", "Key" and $item to the end of an array: <<set $inv.push("Blunt Axe", "Key", $item)>> (push() can insert many values at once.)
*To add the value "Weird Pear" to the start of an array: <<set $inv.unshift("Weird Pear")>>
*To add the values "Blunt Axe", $item, 2, and $weapon to the start of an array: <<set $inv.unshift("Blunt Axe", $item, 2, $weapon)>> (unshift() can also insert many values at once.)
*To remove the value "Weird Pear" from an array: <<set $inv.splice($inv.indexOf("Weird Pear"),1)>>
*To sort an array alphabetically: <<set $inv.sort()>>
*To reverse an array: <<set $inv.reverse()>>
*To remove the first value from an array: <<set $inv.shift()>>
*To remove the last value from an array: <<set $inv.pop()>>
*To remove the first value from an array and set $item to it: <<set $item = $inv.shift()>>
*To remove the last value from an array and set $item to it: <<set $item = $inv.pop()>>

pensive-mosquitoes