Control flow in Toit#
If-statements work in a very similar way to other languages.
The condition is terminated with a colon,
:, and the body
is either a one-liner on the same line, or delimited by indentation:
if i == 42: print "Found the answer!" if i < 100: print "Found a smallish number!"
Else-clauses work in the same way:
if i % 3 == 0: print "fizz" else: print i
ifs can be written with
if i % 3 == 0: if i % 5 == 0: print "fizzbuzz" else: print "fizz" else if i % 5 == 0: print "buzz" else: print i
Sometimes you may prefer the ternary
?: operator instead of small
buzz := i % 5 == 0 if i % 3 == 0: print (buzz ? "fizzbuzz" : "fizz") else if buzz: print "buzz" else: print i
Often, loops are used to iterate over a collection. In this case you should usually use the built-in do method of the Collection class. Some collections also have do --reversed for looping from last to first.
// Loop over all elements in a list: list.do: | element | print element // Loop over elements 10 to 19 of a list, using a slice: list[10..20].do: | element | print element // Loop over all elements, except the first (the one with index zero): list[1..].do: print it
At an even higher level, the built-in collections have some
map that iterate over collections for you
However, sometimes you have to write your own loops. The rest of this section will explain how that works in Toit.
Example of a loop that runs a fixed number of times, given by the
end integer variable.
end.repeat: | i | print i
To use steps, use a
for loop as in:
for i := start; i < end; i += step: print i
while loop to execute a code block as long as a condition is true, as in the following example:
main: max := 5 counter := 0 while counter < max: print counter counter += 1
Sometimes, it is necessary to terminate a
for loop or a
prematurely regardless of the results of the conditional tests. In these cases,
you can use the break statement:
main: max := 50 counter := 0 while counter < max: print counter counter += 1 if counter > 20: break
Similarly you can use the
continue statement to skip the rest of a loop and go straight to the next iteration:
main: sum := 0 for i := 0; i < 10; i++: log sum if sum >= 10: continue sum += i // This line is skipped if sum is already >= 10.
while loops are control structures built into the language, which support
continue. On the other hand,
do are methods that take blocks. Here you have to add the method name (do or repeat) to the continue statement, to indicate which loop you wish to continue.
main: sum := 0 10.repeat: log sum if sum > 10: continue.repeat // Skip the rest of the block. sum += it
break.repeat are not yet implemented.
Sometimes you can instead use a return statement that exits the method completely:
my_function collection: collection.do: if it.is_the_one_we_want: return it // Returns from my_function, also breaks out of the loop. return null
If this is not possible, and you need an actual
break statement, the
repeat can be rewritten with a