Remember which link was clicked in a for-loop

Twine Version: 2.7.1
SugarCube 2.36.1

Hello everyone,

i encountered a, what i think a simple problem, but i cant solve it. I want to remember twine, which link was clicked from a for-loop, on a new site. I tried the following.

StoryInit

<<if not $StudLinkClicked>>
    <<set $StudLinkClicked = new Array(119).fill(false)>>
<</if>>

Selection site:

<<for _i to 0; _i lte 39; _i++>>
<<set _index = _i>>
<<link `"$student_names[_index]$student_surnames[_index]"``"Student"`>>
  <<run $StudLinkClicked[_index] = true>><</link>>
<</for>>

I have two arrays, one with names and one with surnames. I am combining this two to one link.
E.g. array1-name: Sarah. Array2-surname:Parker. Gives the Link “Sarah Parker”.
In therory the variable $StudLinkClicked should save the array location.

The link site “Student”:

<<for _i to 0; _i lte 39; _i++>>
<<if $StudLinkClicked[_i]>>
   The Link for $student_names[_i]$student_surnames[_i] was clicked.
<</if>>
<</for>>

On this site, it shall show me which linked was clicked.

Now the Problem: The variable has always the value 40! And i dont understand why…? Can someone help and explain it to me?

Many thanks :slight_smile:

I may be wrong, but you might need the <<capture>> macro.

The issue you’re having is because of asynchronicity.

The content, the interior, of any macro that is evaluated later, at a different time, can be said to be asynchronous. In other words it’s out-of-sync temporally with the original evaluation of the code that created it.

For example, take the <<link>> macro:

<<link /* LINK_ARGS */>>
    /* CONTENT */
<</link>>

The LINK_ARGS are evaluated as part of running the macro. Thus, the loop variables will have the desired values.

The CONTENT is not evaluated until the player activates the link. Thus, by that point, the loop variables will have the last value set, or unset, before the player interacted with the link.

One way you can solve asynchronicity issues is with the <<capture>> macro. It captures, creates a localized version of, variables’ values for use with asynchronous code.

For example, from your example:

<<for _i to 0; _i lte 39; _i++>>
<<capture _i>>
<<link `"$student_names[_i] $student_surnames[_i]"` "Student">>
    <<run $StudLinkClicked[_i] to true>>
<</link>>
<</capture>>
<</for>>

Thank you so much. It works now!!