Trouble pulling in random name value from array using macro

Fairly new to Twine and semi-new to programming, knowing just a few basics, but learning :slight_smile: Using current Twine and Sugarcube versions as of end of 2022.

I’m running into an issue with a macro that references an array and should pull in a random name.

This is the passage where I’m trying to run the macro and pull in a random name from an array.

<<timed 2s>>Is it <<Names>>? How spooky if I got it right.<</timed>>

Here’s the widget/macro saved in a passage called ‘Names’ and tagged ‘widget’

<<widget "Names">>
<<run $NamesArray.random()>>

And then there is a passage titled “NamesArray” with a list of names, 1 per line.
Tagged ‘array’ not sure if that matters or if it’s just for documentation purposes.

This is my current error code:

Error: <<Names>>: error within widget code (Error: <<run>>: bad evaluation: Cannot read properties of undefined (reading 'random'))

At this point, I’ve tried multiple ways of calling this in, and don’t recall them all (lol), so I’m coming here hoping someone might see what I’m missing!

Ah, a passage isn’t an array. To create an array you’d need to do something like:

<<set $NamesArray to [ "Fred", "Linda", "Bill" ] >>

You probably want to put this in a passage named StoryInit so it’ll be run once when your game starts and will always be set.

And if the names never change, you might want to use the setup object (set with <<set setup.Names to [ ... ]>> and use with <<run setup.Names.random()>>) so it doesn’t get saved in the game’s history every turn. This doesn’t usually matter but if you have a really huge game sometimes they’ll slow down because there’s so much stuff in the history, so it’s not a bad habit to get into.

1 Like

Thanks for that! I had seen in some help post an array in a passage, so I wasn’t sure on that one, good to know that will not work :slight_smile:

So I’ve now tried this but it is returning blank:

<<set setup.Names to ["Samantha", "Perry", "Gandolf", "Mark"]>>

(set in the StoryInit passage)

And then this is in the passage in the game:

<<timed 2s>>Is it <<run setup.Names.random()>>? How spooky if I got it right.<</timed>>

Oops, I’m not thinking. You need to <<print setup.Names.random()>>, not <<run>> it.

1 Like

Thanks! It’s now displaying as expected/hoped :slight_smile: