interrupting a repeat loop

George C Brackett gbrackett at luceatlux.com
Tue Dec 15 13:52:23 EST 2009


Dumb question: could your approach result in too deep a recursion while looping some quick code?

George

On Dec 15, 2009, at 1:43 PM, 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:

local lCount

on countToTen
  add 1 to lCount
  return true
end countToTen

on isItTenYet
  if lCount is 10 then
     return false
  else
     return true
  end if
end isItTenYet

on mouseUp mouseButtonNumber
  iterate "countToTen", "isItTenYet"
  put lCount
end mouseup

This has the benefit of splitting the code to be looped from the code that
says if it should loop more, this way, one could simply change the
isItTenYet command to something that checks for the key press without
touching the countToTen function. This code will work for any kind of loop
and it is nonblocking. You can reuse this for example to create code that
reads from sockets or anything mathematical that loops until some condition
is matched.

Instead of using a simple repeat loop with exit conditions and the like
mixed with the logic that should be looped, this will create some clear
distinctions which leads to more readable code in my experience. Reusable
code is your friend!

Cheers
andre


-- 
http://www.andregarzia.com All We Do Is Code.
_______________________________________________
use-revolution mailing list
use-revolution at lists.runrev.com
Please visit this url to subscribe, unsubscribe and manage your subscription preferences:
http://lists.runrev.com/mailman/listinfo/use-revolution




More information about the use-livecode mailing list