I’m new to IF authoring and struggling a bit with whether to use arrays and/or datamaps. I’m trying to use a passage for text storage, containing one fortune per line. I know I can use the words: macro to create an array from a list of words, but how would I create an array from a list of fortunes so that I could select one randomly? Am I better off just manually adding the fortunes to an array and selecting a random one? The only reason I was thinking of adding the fortunes to a page, one per line, is for legibility.
A real person has two reasons for doing anything … a good reason and
the real reason.
All men have the right to wait in line.
Thanks in advance for any pointers!
Twine Version: 2.3.5
Story Format: Harlowe
Welcome @papyrus. I have modified the “optional tags” assigned to your topic so that they also include the series (version) of the story format, because answers can vary based on this information. I assumed you were using the latest series of Harlowe which is 3.x
1: You could use the
(either:) macro to randomly select an element of an Array, although you will need to use the … spread operator (three consecutive full stops) when passing that Array to the macro.
(set: _list to (a:
'A real person has two reasons for doing anything … a good reason and the real reason.',
'All men have the right to wait in line.'
(set: $fortune to (either: ..._list))
note: You likely noticed that I used a Temporary Variable to store the contents of the Array. I did that because the the story’s History is stored within your web-browser’s Local Storage cache and there is a upper limit to the amount of data each web-app can store within that cache, thus it’s a good idea to only use Story Variables to store data that will change during the reading of the story.
Ideally I would of also stored the randomly selected fortune in a Temporary variable but due to a limitation on Harlowe’s scoping of that variable type what I will suggest next wouldn’t work.
2: Using a child Passage as a reusable “function”
If we added the above code to a Passage then we could use the
(display:) macro to execute that passage’s content like it was a reusable function. The following assumes that the above example was added to a Passage named Random Fortune
(display: "Random Fortune")
Your fortune is "$fortune"
warning: Harlowe’s implementation of both Arrays and DataMap data types are not as efficient as those of some other story formats (like SugarCube’s), which can cause slowdowns if an Author does a lot of “updating of” or “looping through” the contents of those data types. If you plan to do a lot of both of these activities then you may want to consider changing story format you are using.