Possibly a really stupid question this, so thanks for your patience in advance!
I’m looking to create a bit of code that allows me to run a widget a random number of times (say 5-15) in a passage - I’m assuming that would use some kind of <<for>> loop, but I can’t seem to figure out how to do it. I’ve used <<for>> loops with array lengths before no problem, but I just want it to run an amount of times equal to an integer variable if possible.
I’m not a coder and I’m struggling to get my head around this bit of the documentation, so any advice would be appreciated!
do you want the code for running the widget to be in the widget or in the passage only? I can help if I know a bit more what the code is and what you want to accomplish.
as I said to someone else here, sugarcube is “sugary” (sugary meaning “simplified”) javascript, so if you’re struggling with understanding a concept in it, try looking it up for javascript.
Hey - in the passage only! Basically looking for something like:
<<set _customers to random(5,15)>>
<<for (number of times equal to _customers)>>
<<widgetname>>
<</for>>
To be honest I’d been looking at that JS loops page for half an hour before posting in here but I’m not very experienced and struggling to make sense of it!
There are a number of ways you can use the <<for>> macro to achieve the outcome you want…
/* Randomly determine the number of_iterations */
<<set _iterations to random(3, 6)>>
Iterations: _iterations
Using an index variable based condition.
<<for _index to 0; _index < _iterations; _i++>>
call widget
<</for>>
Using a number of iterations based range.
<<for _index range _iterations>>
call widget
<</for>>
Using a temporary instance of an Array with a fixed number of elements.
<<for _value range new Array(_iterations)>>
call widget
<</for>>
note: in each of the above examples, the temporary variable being used to hold the integer based index or the Array element’s value is not being made use of, but it could of been if there was a need to.
I took this out before testing and still got the error - I also copied the following code verbatim from the Sugarcube documentation and got the exact same error, which seems really strange?
<<for _value range 7>>
<<print _value + 1>>.
<</for>>
Doing this gave me the <<for>>: unsupported range expression type: number error again. Weird! I tried removing everything in the JS in case something there was causing an issue but still got the error - seems like any time I use ‘range’ this error occurs.
On a practical level I now have a fix for this specific application so that’s resolved, but am curious if anyone has any ideas what’s causing this error message.