Strange / possibly stupid problem with <<if>>-macro [SugarCube 2]

Hello!
Again, I am struggling with a very basic thing: This code (which uses ChapelRs custom event macro) should trigger <> when

_turns

goes below 1, but the

<< else >>

condition never occurs. Why?

<<set _turns to random(12,15)>>
<<print _turns>>
<div id="price"><span id="priceNumber"></span><br/><span id="turns"></span></div>

 <<if _turns > 0>>
 	<<event 'keydown'>>
 		<<which 32>>
			<<set _currentPriceEur to random (1,99)>>
			<<set _currentPriceCents to random(1,99)>>
			<<set _currentPrice to _currentPriceEur+_currentPriceCents/100>>

       	 <<replace "#priceNumber">>
			 	<span id="priceNumber">_currentPrice</span>
			<</replace>>
			<<set _turns-->>
			<<replace "#turns">>
				<span id="turns">_turns</span>
			<</replace>>
	<</event>>
<<else>>
	<<goto "eval">>
<</if>>

Because _turns will always be greater than zero at the point where <<if _turns > 0>> is checked.

When you do <<set _turns to random(12,15)>>, _turns will get set to 12, 13, 14, or 15, since that’s how the random() function works, and that’s the value it will have at the point where it encounters the <<if>> macro.

Unless you can re-trigger the <<if>> macro, without somehow also setting _turns to 12 to 15 again, then you will never trigger the <<else>>.

This is because the <<event>> macro doesn’t retrigger the code around it. So, if you want to go to the “eval” passage when _turns is less than zero, then you’ll need to check its value and do the <<goto>> within the <<event>> macro when it’s below zero.

Basically, you have it backwards, in that, instead of the <<if>> on the outside and the <<event>> macro on the inside, you should actually have that <<if>> inside of the <<event>> macro.

Hope that helps! :slight_smile:

P.S. To show macros in this forum you need to mark them as “preformatted text” (using the </> button), otherwise all anyone else will see is “<>” (as happened above where you wrote “should trigger <> when”).

Thank you!