For loops with goto's

I am trying to create a little game logic passage, that prints a set of options that are stored in a Map-variable. Each option forwards to another passage using <<goto>> like this:


<<set $DialogChoices to new Map([
      ["Option1", "Passage1"],
      ["Option2", "Passage2"],
      ["Option3", "Passage3"]
      ]) >>
<<for _k, _v range $DialogChoices >>
  <<print "the following " +_k + " leads to " +  _v >>
  <<link "_k">><<goto _v>><</link>>

Passage 1

Passage 2

Passage 3

My idea was that I could dynamically adjust the Map to add / remove options depending on the player’s choices.
Problem: With the above code, all of the links forward to Passage3. I cannot see why, I would be grateful for an explanation.

Twine Version: tweego
Story Format: Sugarcube 2

Yeah…SugarCube isn’t scoped that way: the <<goto _v>> isn’t evaluated until you click the link, and by that time, the loop is finished and _v is set to “Passage3”. So you need to use the <<capture>> macro to save a copy of _v.

<<for _k, _v range $DialogChoices >>
  <<print "the following " +_k + " leads to " +  _v >>
  <<capture _v>><<link "_k">><<goto _v>><</link>><</capture>>

Thank you so much! I was suspecting that something like this is happening but being in the learning phase still, I could not figure out a workaround.

Is there any way to properly debug Sugarcube macros? In the above code I added a <<print>> statement. Of course, it was not helpful in this case because of the lazy evaluation of the goto as Josh explained.

You don’t need <<goto>> here as <<link>> takes a passage argument. For example:

<<capture _v>><<link _k _v>><</link>><</capture>>


It would depend on what you’re looking for. There is Test mode.

In this case, logging to the console would have worked:

<<capture _v>><<link _k _v>>
    <<run console.log('<<link>> "' + _k + '" leads to "' +  _v + '"')>>
1 Like