SARL provides four types of loop statements.
The for loop is used to execute a certain expression for each element of an array or an instance of Iterable
.
The for’s variable is local and final, hence cannot be updated.
The type of a for loop is void
. The type of the local variable can be inferred from the
iterable or array that is processed, e.g. in the following example v
is of type String
.
var tab : String[]
for (v : tab) {
println(v)
}
You could specify the expected type for the local variable with the as
following the local variable:
for (v as String : tab) {
println(v)
}
The traditional for loop is very similar to the one known from Java, or even C.
When executed, it first executes the init-expression, where local variables can be
declared. Next the predicate is executed and if it evaluates to true
, the
body-expression is executed. On any subsequent iterations the update-expression
is executed instead of the init-expression. This happens until the predicate
returns false
. The type of a for loop is void
.
for (var i = 0; i<123; i++) {
println(i)
}
A while loop is used to execute a certain expression unless the predicate is evaluated to
false
. The type of a while loop is void
.
var i = 0
while (i<123) {
println(i)
i++
}
A while loop is used to execute a certain expression unless the predicate is evaluated
to false
. The difference to the while loop is that the execution starts by
executing the block once before evaluating the predicate for the first time.
The type of a while loop is void
.
var i = 0
do {
println(i)
i++
}
while (i<123)
The break
keyword is provides for breaking the enclosing loop.
When this keyword is run, the control flow exits for the nearest
enclosing loop, and run the statement that is just following the loop
expression in the sequence of instructions.
for (v : tab) {
if (v == 1) {
break
}
}
The continue
keyword is provides for stopping the execution of the
current iteration into loop, and jumping to the next iteration.
When this keyword is run, the control flow jumps to the next iteration
for the nearest enclosing loop, and run the statement that is just at
the beginning of the loop’s block expression.
for (v : tab) {
if (v == 1) {
continue
}
}
This documentation is inspired by the documentations from the Xtext and Xtend projects.
Copyright © 2014-2024 SARL.io, the Original Authors and Main Authors.
Documentation text and medias are licensed under the Creative Common CC-BY-SA-4.0; you may not use this file except in compliance with CC-BY-SA-4.0. You may obtain a copy of CC-BY-4.0.
Examples of SARL code are licensed under the Apache License, Version 2.0; you may not use this file except in compliance with the Apache License. You may obtain a copy of the Apache License.
You are free to reproduce the content of this page on copyleft websites such as Wikipedia.
Generated with the translator docs.generator 0.14.0.