0 votes
by (8.9k points)
edited by

So I have this array:

<<set setup.orcDescriptions to [
   'a foul',
   'a brutal-looking',
   'a savage',
   'an angry'
]>>

I know I can get a random one of these with the following code in a passage:

You round the corner and see <<print Array.random(setup.orcDescriptions)>> orc!

However I have an inkling that I could do this better with a macro or a widget, so that code like this would work:

You round the corner and see <<orcDescriptions>> orc!

It seems like the latter approach is better, but I don't know how to do it.  Do YOU?

1 Answer

+1 vote
by (159k points)
selected by
 
Best answer

You don't need to use the Javascript Array.random() function to return an random item from an Array, you can use SugarCube's built in <Array>.random() function instead.

You round the corner and see <<print setup.orcDescriptions.random()>> orc!

To convert the above into a <<widget>> simply do the following:

a. Add a new Passage to your story and assign it a widget tag, this can now be used to store all your story's widget definitions. The actual name of this Passage is not important, I generally name mine Widgets for convenience.

b. Add the following TwineScript to this new Passage, it defines a widget named OrcDescription which outputs a randomly selected item from the setup.orcDescriptions Array.

<<widget "OrcDescription">>\
<<= setup.orcDescriptions.random()>>\
<</widget>>

c. You can use the new <<OrcDescription>> widget like so.

You round the corner and see <<OrcDescription>> orc!

 

by (8.9k points)
Perfect, thanks greyelf!
...