interrupting a repeat loop

Alex Tweedly alex at tweedly.net
Tue Dec 15 19:09:56 EST 2009


Andre Garzia wrote:
> Hi Folks,
>
> this been answered in many ways already but I thought I'd chime in and try
> to answer it in a different way. The key is to think of reusable code, every
> now and them we keep rewritting the same pieces over and over again. How do
> we create a generic thing that will:
>
> 1) Run some code in a loop
> 2) Enable us to stop this execution when something happen
>
> If speed is not the main issue here, then we can approach this with a more
> flexible way by creating a group of functions that will enable a generic
> handler to be executed until something else make it stop. We will use the
> new dispatch calls for that.
>
> command iterate pHandlerToLoop, pHandlerThatInterrupts
>    dispatch pHandlerThatInterrupts
>    if the result is true then
>       dispatch pHandlerToLoop
>       if the result is true then
>          dispatch iterate with pHandlerToLoop, pHandlerThatInterrupts
>       end if
>    end if
> end iterate
>
> This code will first call a command to check if the loop should be executed,
> this command should return true or false. If it is true then it will call
> the loop command once and if the loop command returned true, it will call
> itself again. This code will loop and will exit the loop if any of two
> things happen, the command that interrupts return false or the command that
> loops return false, for example, let us count to ten using this code:
>
>   
Nice. But as George said, you will hit recursion limits.

And the dispatch to iterate (i.e. to itself) is a simple tail recursion 
- which you can eliminate easily.

AFAICT, this is equivalent and has no recursion issues.
> command iterate pHandlerToLoop, pHandlerThatInterrupts
>    repeat forever
>       dispatch pHandlerThatInterrupts
>       if the result is false then exit iterate
>       dispatch pHandlerToLoop
>       if the result is false then exit iterate
>    end repeat
> end iterate


-- Alex.



More information about the Use-livecode mailing list