repeat with each woord currentWord in myString

Brian Yennie briany at qldlearning.com
Sat Mar 20 16:00:25 EST 2004


> Hi, List.  I understand that there is a way of replacing the old 
> "repeat with x=1 to 10" statement with something like
> "repeat with each woord currentWord in myString"
> How exactly is this used?  This is foreign to me.
> Thanks!

Imagine you are doing something like this:

repeat with i=1 to (the number of words in someVariable)
    put word i of someVariable into someWord
    doSomething someWord
end repeat

These scripts are pretty common- iterating over all of the chunks in a 
container. They can get a bit inefficient with large variables. For 
example, when you ask for "item 100000" of something, Rev is forced to 
search from the beginning of the string, counting items until it finds 
the 100,000th one. And the next time through, it starts from the 
beginning to find 100,001, and so on. Since Rev doesn't actually know 
that you are always going to just look for the _next_ item, it can't 
just save your spot.

And so... (drum roll please)... it would be much more efficient if 
there were some way to grab each chunk sequentially, without the engine 
being forced to re-count from the beginning every time through. Thus, a 
special construct:

repeat for each word someWord in someVariable
    doSomething someWord
end repeat

This will produce the exact same results* as the previous script, but 
will be much faster for large data sets (and looks nice and keeps you 
from screwing up your counter accidentally, etc)

Note that you can also repeat "for each line", "for each item", and 
even "for each element" (the elements of an array, try it!). Combine 
those with all of the possible things you can pass as containers, and 
you get a pretty fast, flexible way to process consecutive chunks (or 
elements) of the same thing.

* Of course, the "i" variable won't be set, but you can get it back if 
you really want by setting it's value beforehand and adding 1 to it in 
each iteration of the loop. This will still be quite fast.

Hope that helps,

- Brian



More information about the use-livecode mailing list