Beginner question:Having trouble with array / link-macro (Sugarcube 2.30)

Hello,

I am having a little dumb problem which I cannot solve by myself. Could sb look over it?
I start with two arrays:

<<set $sequenceMap to [
["x", "x", "x", "16", "9"],
["15", "x", "x", "3", "11"],
["8", "5", "x", "12", "x"],
["6", "4", "2", "13", "x"],
["1", "10", "7", "14", "x"]>>
<<set $itemCounter to [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]>>

Now this widget should iterate through $sequenceMap and put link-macro for every “non-x” value and check, if the links are clicked in correct sequence (1,2,3,…):

<<widget "generateClickArray">>\
	<<for _i to 0; _i lt $sequenceMap.length; _i++>>\
		<<for _j to 0; _j lt $sequenceMap[_i].length; _j++>>\
			<<set _linkText to $sequenceMap[_i][_j]>>\
			<<if $sequenceMap[_i][_j] neq "x">>\
				<<link _linkText>>\
					<<if _linkText eq $itemCounter[0]>>
						<<run UI.alert("Click!")>>\
						<<set $itemCounter.deleteAt(0)>>
					<<else>>
						<<run UI.alert("Wrong!")>>\
					<</if>>
				<</link>>\
			<</if>>\
		<</for>>\
		<br/>
	<</for>>\
<</widget>>

Link-macros are shown correctly, but widget always alerts “wrong”. But when I replace inner < if> macro with e.g. <<run UI.alert( _linkText)>> it alerts “1” for link “1”, which equals $itemCounter[0], no?

I am sure there is something very obvious I must be missing…

I wouldn’t say “obvious”, but the problem is that, by the time the player clicks on any of those links, the values of _i and _j have changed.

To prevent that you need to use the <<capture>> macro to “capture” those value. Just wrap the code inside the widget within <<capture _i _j>> ... <</capture>> then the code inside it will use those variables’ values at the time the code is created within the loop, instead of their values at the time the player clicks on them.

I have some <<capture>> sample code which helps explain how it works if you need any further help using it. (Click “Jump to Start” on the UI bar to see other sample code there.)

Hope that helps! :slight_smile:

1 Like

@wolodymyr
This is also true for the value of the _linkText temporary variable, so you would either:
1: need to add _linkText to the list of variables you are capturing.
2: change the <<if _linkText eq $itemCounter[0]>> code within the generated link to reference $sequenceMap[_i][_j] instead of _linkText.

1 Like

Thank you!