Wiki
Version 4 (modified by hopscc, 14 years ago)

--

Numeric For Statement

Grammar

for <variable> in [<start>:]<stop>[:<step>]
    <statements>

If <start> is not specified it defaults to 0.

If <step> is not specified it defaults to 1.

For each iteration <variable> gets a value beginning at <start> incrementing by <step> and ending when the <stop> value is reached or exceeded ( or a break statement is encountered).

the loop iteration is equivalent to

<variable> = start
while <variable> < <stop>
    ... statements..
    <variable> += <step>

i.e The <stop> value is exclusive to the loop counter range.

Inside the statements, a break statement will exit the loop and a continue statement will skip the remaining statements. In either case, an if statement is used to control when the loop is broken or continued (otherwise it would be pointless to have further statements in the loop).

Examples

  for i in 1:10
     print i   # prints values 1,2,3,4,5,6,7,8,9

  for i in 1 : 10  # can have spaces around :
     print i

  for i in 5
    print i    # prints values 0,1,2,3,4

  for i in 7:5:-1
    print i    # prints values 7,6

  for e in 20:31:2
    print i    # prints even numbers between 20 and 30 inclusive

  for f in 7:5
    print f    # never executed

  for i in someList.count
    print i    # print the list indexes

Old Syntax

The old-numeric-for syntax is deprecated.

 old-numeric-for-statement =
   for <variable> = <start> .. <stop> [ ++ | -- <step> ] 
       <statements>