Using 'for each' to modify a container

Jim Ault JimAultWins at yahoo.com
Wed Oct 11 11:30:32 EDT 2006



On 10/11/06 6:34 AM, "Bill Marriott" <wjm at wjm.org> wrote:

> You shouldn't try to change the tires while the car is moving, and you
> shouldn't try to modify the entity being used as the basis of a repeat loop.
> 
> For example, if you were to say
> 
> repeat with i = 1 to 20
> end repeat
> 
> you shouldn't try to modify i within the loop.
> 
> If you say
> 
> repeat for each line theLine in myVariable
> end repeat
> 
> you shouldn't try to modify myVariable within the loop.
> 
> There are probably many possibilities for your solution, but I would
> probably do it this way:
> 
> put empty into newContainer
> repeat for each line thisLine in vContainer
>   put doSomeFunction(item -2 of thisLine) into item -2 of thisLine
>   put thisLine & return after newContainer
> end repeat
> put char 1 to -2 of newContainer into vContainer

Actually, I try to avoid changing the value returned by the 'for each'
--original version
> put empty into newContainer
> repeat for each line thisLine in vContainer
>   put doSomeFunction(item -2 of thisLine) into item -2 of thisLine
>   put thisLine & return after newContainer
> end repeat
> put char 1 to -2 of newContainer into vContainer
>
--my preference is 
> put empty into newContainer
> repeat for each line thisLine in vContainer
   put doSomeFunction(item -2 of thisLine)&cr after newContainer
> end repeat
> put char 1 to -2 of newContainer into vContainer

I think the reason that 'for each' is so fast is that it scans the
"vContainer" memory space, returns those characters, and is not meant to be
modified.  My experience is that it is unpredictable to rely on the changed
value of 'thisLine'

Further, I don't reuse the name 'thisLine' in the next instance of a repeat
for each loop in the *same handler*, but change the name to avoid conflict,
such as 'thisline', 'thisline1', 'thisLine2'.  Again, unpredictable results
occasionally.

Jim Ault
Las Vegas





More information about the Use-livecode mailing list