Re: Things I thought I knew, but didn't - variable scope in repeat loops
Re: Things I thought I knew, but didn't - variable scope in repeat loops
- Subject: Re: Things I thought I knew, but didn't - variable scope in repeat loops
- From: Axel Luttgens <email@hidden>
- Date: Thu, 25 Dec 2008 11:12:11 +0100
Le 25 déc. 08 à 09:04, Richard Rönnbäck a écrit :
For as long as I can remember I have been very cautious not to use
the same
variable name in nested repeat loops, or for that matter not to use
the
counter variable (what is the proper name for it btw?) anywhere else
in the
script, thinking that AppleScript would confuse what the current
value of
the counter is.
In other words, I would never have done this:
[...]
Thinking that "i" would inherit the value from the script, the outer
loop,
or the inner loop, messing up the counter completely
Then, by coincidence, I stumbled upon something that made me take a
closer a
look at it, and I found, to my complete surprise, that AppleScript
does
exactly what I want, that is, it "knows" how to scope the variable,
in this
case "i" to only the current repeat loop, as the log below shows:
[...]
My question is - are these rules for scope documented anywhere, or can
someone explain how, and why the variable scoping works the way it
does?
Hello Richard,
In fact, one has managed to create at the same level of the script
(its implicit run handler) two variables bearing the same name "i":
- a variable implicitly declared and created as a global one, through
the set statement,
- a variable implicitly declared and created as a local one, through
the use of the repeat statement.
This may appear more clearly through a slight variant of your script:
set i to 10
repeat with i from 1 to i - 8
log {" Outer loop", my i, i}
repeat with i from 20 to i + 20
log {" Inner loop", my i, i}
end repeat
end repeat
log {"After looping", my i, i}
A far as the documentation for the behavior of the repeat statement is
concerned, the ASLG states (p. 207 in its current version):
You can use an existing variable as the loop variable in a repeat
with loopVariable (from startValue to stopValue) statement or
define a new one in the statement. In either case, the loop
variable is defined outside the loop. You can change the value
of the loop variable inside the loop body but it will get reset
to the next loop value the next time through the loop. After the
loop completes, the loop variable retains its last value.
AppleScript evaluates startValue, stopValue, and stepValue when it
begins executing the loop and stores the values internally. As a
result, if you change the values in the body of the loop, it
doesn’t change the execution of the loop.
HTH,
Axel _______________________________________________
Do not post admin requests to the list. They will be ignored.
AppleScript-Users mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
Archives: http://lists.apple.com/archives/applescript-users
This email sent to email@hidden