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:
Else-clauses work in the same way:
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.
// Create a list containing 30 element, each slot set to its index. list := List 30: it // 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.
If you simply want to execute a block of code multiple times you can use
which is a method on the int class
that takes a Toit block.
Example of a loop that runs a fixed number of times, given by the
end integer variable.
To use steps, use a
for loop as in:
while loop to execute a code block as long as a condition is true, as in the following example:
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:
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 // This line is skipped if sum is already >= 10. sum += i
while loops are control structures built into the language,
continue. On the other hand,
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: // Returns from my_function, also breaks out of the // loop. return it return null
If this is not possible, and you need an actual
break statement, the
repeat can be rewritten with a