# Counters

It may so happen that you may want to add counter in your loops. So let's have a look at how we can implement counters in AppleScript.

Script [13.4.1]:

repeat with counter from 1 to 5
say "I ran " & counter & " kilometers."
end repeat


Explanation: In the above repeat command, I have added a counter which will increment from 1 to 5 every time the repeat command is executed. The repeat section will execute as long as counter is not >5.

I ran counter kilometers will be spoken 5 times.

Script [13.4.2]:

repeat with counter from 1 to 5
say "I ran " & counter & " kilometers."
set counter to (counter + 1)
end repeat


Explanation: The output remans same. The sentence is spoken 5 times. You must be wondering, how is this possible even after incrementing counter.

Well, in repeat block the counter variables value cannot be changed.

Script [13.4.3]:

repeat with counter from 1 to 5 by 2
say "I ran " & counter & " kilometers."
end repeat


Explanation: In 13.4.2, we saw that counter’s value cannot be changed inside the repeat block. However you can specify by n where n is an integer. by n, simply means incrementing by n.

In the above example, I am incrementing counter by 2 excluding the first time when it executes.

The sentence will be spoken 3 times that is counter = 1, 3 & 5.

Script [13.4.4]:

tell application "Finder"
set folderPath to choose folder "Select Folder"
set folderList to every folder of folderPath
end tell


Explanation: This is a simple script where I am creating a folder list of all folders present in the folder selected.

But if you remember, output was big and it was in a format that Finder understood. Let’s have a look at the output.

Figure 13.4.4 Folder List

This is not something what user wants. He wants simple output with name of folders. How do we do it? It's simple, we use counters...

Script [13.4.5]:

tell application "Finder"
set folderPath to choose folder "Select Folder"
set folderList to every folder of folderPath
end tell
set actualList to {}
repeat with counter in folderList
set fName to name of counter
set actualList to actualList & fName
end repeat


Explanation: This is a simple script where I am creating a folder list of all folders present in the folder selected. folderList will store the Finder formatted list of folders.

So I create another list named actualList and keep it empty. Then I use repeat command along with counter in the folderList. So every item of folderList can be called using counter.

Then I create a variable fName (folder name) which will store the name of item at index counter (1, 2...). Then I append actualList with actualList and fName.

I append it with actualList also so that previous data is also included or else only the latest folder Name (fName) will be added.

Figure 13.4.5 Folders in a Folder