I need a way to iterate over a range of numbers in Dialog—that is, I need to bind a variable to 0, then to 1, then to 2, all the way up to N. Something equivalent to *($N is one of [0 1 2 3 4])…except that N is a variable, not a compile-time constant. (The order isn’t important, as long as all the numbers are found.)
This is my current approach:
(have $N count down from $Total)
($N = $Total)
(or)
($Total minus 1 into $Tm1)
*(have $N count down from $Tm1)
The subtraction will fail when it reaches 0, ending the recursion. But I’m not sure if there’s some better way to do this using built-in features.
Is there a better way to be doing this?
Bonus: more versatile version, matching Inform’s “repeat with VAR running from LOW to HIGH”.
(have $N count up from $Low to $High)
($N = $Low)
(or)
($Low plus 1 into $Lp1)
~($Lp1 > $High)
*(have $N count up from $Lp1 to $High)
It depends on how big a range you need. As I understand it, the recursion means you need (High-Low) amount of stack slots (and space for each local var too), so that will limit you to fairly small ranges I think.
You can reduce the amount of stack used with a binary search algorithm – where each recursion is over roughly half of the previous interval.
If you needed to iterate over a very large range, then using (repeat forever) and modifying a global variable may be the only way.
Fortunately, dialogc does tail recursion optimization (though dgdebug doesn’t), so I don’t expect that to be an issue—the recursive call is in tail position, so it shouldn’t need any more stack space.