3.5 Control Flow
Conditions
Conditional statements allow you to execute different blocks of code based on specific conditions.
The following example demonstrates an if statement that checks the value of a variable a and updates it accordingly:
let a: u8 = 1u8;
if (a == 1u8) {
a += 1u8;
}
else if (a == 2u8) {
a += 2u8;
}
else {
a += 3u8;
}In this case:
If
ais1, it increments by1.If
ais2, it increments by2.Otherwise, it increments by
3.
Assert
Assertion are special instructions that allows to stop the execution of a transition under a specific condition.
They can be used simply as follows:
This code will always fail when condition is false, and run fine when condition is true.
Here is a more useful example:
This transition won't ever be able to be called by none other than aleo1hn9z4zt6awd6ts9zn8ppkwwvjwrg04ax48krd0fgnnzu6ezg9qxst3v26j .
assert are extremely useful, in particular to validate user inputs.
Loops
A for loop is used to iterate over a range of values. The loop runs a specific number of times, making it ideal for iterating over sequences or performing repeated operations.
The loop variable is declared with a type.
The loop iterates from the
lower_boundto theupper_bound- 1.The bounds must be integer constants of the same type.
The
lower_boundmust always be less than theupper_bound.
This example demonstrates a simple for loop that counts from 0 to 4 and keeps track of the count:
The loop runs from
0to4, iterating5times.countis incremented during each iteration.The function returns
5.
On Leo loops always include a finite amount of iterations that are known at compile time. For instance the upper or lower bound of the loop cannot be an input of the transition.
While this code is invalid:
Something like this could be used instead:
Last updated