Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Arrays, for loops and multiple passages

First of all, this is in sugarcube.
I have a question:
Assuming I have an array,
$myArray to [0, 1, 2, 3, 4, 5]
, and I want to display this as follows:
<<for $i to 0; $i < $myArray.length; $i++>>
<<print $myArray[$i]>>
[[Pick this element|nextPassage][$foo to $myArray[$i]]]
<</for>>

Now, if you'll try this, you'll learn that this code does not work. The reason for this is that the variable $i contains the value of $myArray.length, since the for loop was concluded. That is to say, even though the following is printed:
0
Pick this element
1
Pick this element
...
5
Pick this element
No matter which element you pick, the value of $foo will always be 5.

Is there a workaround for this?

Comments

  • edited June 2016
    This is because the values of both the $i and $myArray variables in your Setter Link are determined when the link is selected, not when the link was created.

    This means that in your example the value of $i will always be equal to 6 ($myArray.length) which means that you are trying to assign $myArray[6] to $foo and that element does not exist.

    You can use a <<print>> macro to dynamically create your Setter Link which allows to to use the correct value of $i with each link.
    <<for $i to 0; $i < $myArray.length; $i++>>
    <<print $myArray[$i]>>
    <<print "[[Pick this element|nextPassage][$foo to $myArray[" + $i + "]]]">>
    <</for>>
    
  • Ah, again with the magical print macros.
    Thanks a bunch!
Sign In or Register to comment.