0 votes
by (640 points)
Hi all I have a question about how arrays work.

I know you can set up and array like this:

<<set $weekDays=["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]>>

So let's say that I want to setup a button that advances $weekDays by 1 day so:

Before pressing the button $day = Monday

and after $day = Tuesday.

I know how to use <<button>>, just not sure about the syntax needed to use the actual array itself.

Thanks for you help!

1 Answer

+2 votes
by (1.2k points)
selected by
 
Best answer

You were looking to build a time system I seem to recall and I personally wouldn't set it up that way as advancing things is probably easier if it worked a bit like this:

<<silently>>

/* Initialise the text strings for days of the week */
<<set $weekDay to ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]>>

/* 0 = first item in the array, so Monday */
<<set $day to 0>>

<</silently>>

/* Setup an element to show the day of the week and have it showing the current day */
<div id="dayOfWeek">$weekDay[$day]</div>

/* A button to increment the value */
<<button "advance to next day">>

/* Add one to the day $value */
<<set $day++>>

/* Is the day value more than 6 now? That means it's a new week - reset it to 0 */
<<if $day gt 6>>
	<<set $day to 0>>
<</if>>

/* Replace the old reported day of the week with the new one */
<<replace "#dayOfWeek">>$weekDay[$day]<</replace>>
<</button>>

I've tested that code and it does work but it might of course not be what you're after laugh

by (640 points)
This is perfect! Thanks so much!!
by (1.2k points)
Glad I could help!
by (153k points)

The $weekDay (and the related $weekDays) story variable in the above example(s) never changes it's value. Any value that behaves like that should be defined on the special setup object variable instead, this will result in it being removed from the History & Save systems.

1. Replace your current initialisation of the $weekDay story variable with the following:

<<set setup.weekDay to ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]>>

2. Replace all the other occurrences of the $weekDay story variable with a reference to the setup.weekDay like so:

<div id="dayOfWeek">$weekDay[$day]</div>

/% Becomes the following... %/
<div id="dayOfWeek">setup.weekDay[$day]</div>

 

Welcome to Twine Q&A, where you can ask questions and receive answers from other members of the community.

You can also find hints and information on Twine on the official wiki and the old forums archive.

See a spam question? Flag it instead of downvoting. A question flagged enough times will automatically be hidden while moderators review it.
...