Things I thought I knew, but didn't - variable scope in repeat loops
Things I thought I knew, but didn't - variable scope in repeat loops
- Subject: Things I thought I knew, but didn't - variable scope in repeat loops
- From: Richard Rönnbäck <email@hidden>
- Date: Thu, 25 Dec 2008 09:04:36 +0100
- Thread-topic: Things I thought I knew, but didn't - variable scope in repeat loops
Title: Things I thought I knew, but didn't - variable scope in repeat loops
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:
set i to 10
set myList to {1, 2, 3, 4}
repeat with i from 1 to count myList
log "script's " & i of me
log "outer " & i
repeat with i from 1 to count myList
log "inner " & i
end repeat
end repeat
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:
-- started
(*script's 10*)
(*outer 1*)
(*inner 1*)
(*inner 2*)
(*inner 3*)
(*inner 4*)
(*script's 10*)
(*outer 2*)
(*inner 1*)
(*inner 2*)
(*inner 3*)
(*inner 4*)
(*script's 10*)
(*outer 3*)
(*inner 1*)
(*inner 2*)
(*inner 3*)
(*inner 4*)
(*script's 10*)
(*outer 4*)
(*inner 1*)
(*inner 2*)
(*inner 3*)
(*inner 4*)
-- stopped
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?
rgds
// Richard
_______________________________________________
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