-
Notifications
You must be signed in to change notification settings - Fork 81
Loop execution
In Jai loops are one of the most powerful features, they are both powerful and concise.
The for loops apply to situations where the number of iterations is known before the execution. So for most cases.
For loops are used widely to iterate over arrays.
An iteration over arrays, somewhat semantically similar to the 'C' style, that uses indexes it is still possible.
lines: [..] string;
lines = read_lines(file_name);
lines_number := lines.count;
// Perform N operations iterating over a range of numbers
i := 0;
for 1..lines_number print_line(lines[i++]);
// Perform N operations iterating over a range of numbers and assigning a
// name to the iterator
for i:1..rows_number print_line(rows[i-1]);
Instead in Jai, we can leverage a simple concept of iterator and so it is possible to use the keywords 'it' and 'it_index' to get direct access to the items of the arrays. This allows extremely coincise and effective syntax avoiding lambdas or high order functions used in other languages.
ROW_SIZE :: 10;
row_cells : [ROW_SIZE] int;
// Old style using an external index
// Iterate over the array using an index and a range operator
for i: 0..ROW_SIZE-1 row_cells[i]= random_int(1,100);
// Alternative Jai iterator-index way
// Iterate over the array using the 'it_index' keyword
// 'it_index' is a zero based number from the first to the last element of the array
for rows_cells row_cells[it_index] = random_int(1,100);
// Preferred Jai iterator way
// Iterate over the array using the 'it' keyword
// Here 'it' means 'row_cells[it_index]'
for rows_cells it = random_int(1,100);
// Alternative Jai iterator renaming way
// Iterate over the array using a renamed iterator
// Here 'cell' is an alias of 'it' keyword and still means 'row_cells[it_index]'
for cell: rows_cells {
cell = random_int(1,100);
}
This is possible because in Jai the arrays are data structures that not only store the data but also the number of the contained items. See the arrays page for further details.
It is possible to interrupt completely an iteration using the break
keyword.
for entities {
if need_update(it) break;
else {
...
}
}
Instead, it is possible to skip an iteration using the continue
keyword.
for entities {
if it.updated continue;
else {
...
}
}
The while loops apply to situations where the number o iterations depend on external conditions
These documents were verified using Grammarly free browser plugin for Chrome. Please use some spell checker before submitting new content.
- Variables and assignments
- Language data types
- Simple user-defined data types
- Expressions and operators
- Type-casting
- Pointers
- Declarations
- Arguments / Parameters
- Return values
- Overloading / Polymorhism
- Advanced features
- Lambdas
- Arrays
- Strings
- Composition of Structs
- Metaprogramming
- Templates / Generics