LessonsBeginner: First stepsLesson 13

Repeat for each

Walk through every character, word, item or line of a value, the fastest and clearest loop in xTalk.

  • Beginner
  • Lesson 13 of 83
  • About 8 minutes
  • 5 examples

One piece at a time

Very often you want to do something with every part of a value: each word of a sentence, each line of a list. repeat for each hands you the parts one by one, in a variable you name.

ExampleRun it in the playground
repeat for each word tWord in "the quick brown fox"
   put tWord && "has" && the number of chars of tWord && "letters"
end repeat
Output
the has 3 letters
quick has 5 letters
brown has 5 letters
fox has 3 letters

Every character

Counting vowels, and turning a word round, one character at a time:

ExampleRun it in the playground
put 0 into tVowels
repeat for each char tChar in "programming is fun"
   if tChar is among the chars of "aeiou" then add 1 to tVowels
end repeat
put tVowels && "vowels"
repeat for each char tChar in "stressed"
   put tChar before tBackwards
end repeat
put tBackwards
Output
5 vowels
desserts

Items and lines

An item is a piece of a list separated by commas; a line is a piece separated by new lines. Both are everywhere in xTalk: the next lesson is about them. Looping over them is how you work through a list:

ExampleRun it in the playground
put 0 into tTotal
repeat for each item tPrice in "2.50,3.75,1.25"
   add tPrice to tTotal
end repeat
put "Total:" && tTotal
put "Ada,36" & return & "Grace,85" into tPeople
repeat for each line tPerson in tPeople
   put item 1 of tPerson && "is" && item 2 of tPerson
end repeat
Output
Total: 7.5
Ada is 36
Grace is 85

Why it is the best loop for a list

You could write the same with repeat with i = 1 to the number of lines of tList and line i of tList, but for a long list that is much slower: to find line 5,000, xTalk has to count through the 4,999 before it, every time. repeat for each walks the list once. On a list of thousands of lines the difference is seconds against a blink.

Arrays: each key, each element

The same loop works on arrays, which you will meet in Arrays: repeat for each key tKey in tArray gives each key, and repeat for each element tValue in tArray each value.

ExampleRun it in the playground
put 12 into tScores["Ada"]
put 30 into tScores["Grace"]
put 0 into tTotal
repeat for each element tScore in tScores
   add tScore to tTotal
end repeat
put tTotal
Output
42

Try it yourself

Make the initials of a name: put the first character of each word of Grace Brewster Murray Hopper after a variable, and put it.

Show a solution
ExampleRun it in the playground
put empty into tInitials
repeat for each word tWord in "Grace Brewster Murray Hopper"
   put char 1 of tWord after tInitials
end repeat
put tInitials
Output
GBMH

Words in this lesson

Each one finds every lesson that uses it. The Dictionary has the whole story of each, with its syntax and more examples.