0 votes
by (140 points)

I'm trying to do some Magic select in SugarCube2

<<set $Am to [	{
	name:"Magik1",
	ds:"Description 1",
	qtd:0
		},{
	name:"Magik2",
	ds:"Description 2",
	qtd:0
		},{
	name:"Magik3",
	ds:"Description 3",
	qtd:0
		}]>>

<<for _i to 0; _i < $Am.length; _i++>>
	<il>$Am[_i].name</il>\
	<<nobr>>
		<<link "[-]">>
			<<capture $Am[_i].qtd>>
				<<set $Am[_i].qtd -= 1>>
				<<replace "#"+$Am[_i].name>>
					$Am[_i].qtd
				<</replace>>
			<</capture>>
		<</link>>
		<span @id="$Am[_i].name">$Am[_i].qtd</span>
		[+]
	<</nobr>>
	<blockquote>$Am[_i].ds</blockquote>
<</for>>

Am I using <<capture>> wrong somehow?

My Passage doesnt read $Am[_i].qtd inside link macro (Cannot read property 'qtd' of undefined.)

I'm not sure about this replace, but its a question for another time.

I will be grateful for any help.

 

1 Answer

0 votes
by (159k points)

There are a number of issues with your example.

1. The placement of your <<capture>> macro and the variable you are trying to capture.

If you look at the first example in the linked documentation you will notice that the interactive <<linkappend>> macro is within the <<capture>> macro's body, and not the other way around like you have with your <<link>> macro. You will also notice (and the documentation states this) that the <<capture>> is capturing a (story) variable and not a property of one of the elements contained within an Array.

Because the contents of your $Am variable should still be available at the time the end-user selects one of your link then you only need to capture the index of the related Array element.

2. Not forcing the evaluation of the String concatination you are passing to the <<replace>> macro.

If you look at the Passing an expression as an argument section of the Macro Arguments documentation you will learn about the issues with trying to execute code like the following.

<<replace "#" + $Am[_i].name>>

You need to use back-quotes to force the String concatination to be done before the resulting String is passaged to the <<replace>> macro.

The following is a modified version of your example with the above issues fixed.

<<for _i to 0; _i < $Am.length; _i++>>
	<il>$Am[_i].name</il>\
	<<nobr>>
		<<capture _i>>
			<<link "[-]">>
				<<set $Am[_i].qtd -= 1>>
				<<replace `"#" + $Am[_i].name`>>
					$Am[_i].qtd
				<</replace>>
			<</link>>
		<</capture>>
		<span @id="$Am[_i].name">$Am[_i].qtd</span>
		[+]
	<</nobr>>
	<blockquote>$Am[_i].ds</blockquote>
<</for>>

 

by (140 points)
Thank you, it was very helpful!
...