The template language can now loop over an integer range using a new range() function.
The (condensed) grammar for loops over lists and integers is:
Code:
for_expr ::= for_list | for_range
for_list ::= 'for' identifier 'in' list_expr
[ 'separator' separator_expr ] ':' expression_list 'rof'
for_range ::= 'for' identifier 'in' range_expr ':' expression_list 'rof'
range_expr ::= 'range' '(' [ start_expr ',' ] stop_expr
[ ',' step_expr [ ',' limit_expr ] ] ')'
The new range() function generates a sequence of integer values using the
Python 3 builtin range function. The limit_expr parameter is added to prevent (near-)infinite loops. If step_expr is positive then the loop counts up. If it is negative the loop counts down. It cannot be zero. When positive, generation stops when
Code:
current_value + step_expr >= stop_expr
The list is empty (no iteration) if start_expr >= stop_expr. If the number if integers in the sequence exceeds limit_expr (default 1000) an error is raised.
In the context of a for loop the list isn't actually generated, improving performance and memory usage. In any other context the range() function generates and returns the list.
Example: this loop uppercases every second letter in the title:
Code:
program:
res = '';
for i in range(strlen($title)):
c = substr($title, i, i+1);
res = strcat(res, if mod(i, 2) == 0 then uppercase(c) else c fi)
rof
Here is the same example using all the range() parameters:
Code:
program:
res = '';
for i in range(0, strlen($title), 1, 100):
c = substr($title, i, i+1);
res = strcat(res, if mod(i, 2) == 0 then uppercase(c) else c fi)
rof
This example counts the number of unique alphanumeric characters in the title:
Code:
program:
t = $title;
res = '';
for i in range(strlen(t)):
c = lowercase(substr(t, i, i+1));
if '\w' in c then
res = list_join(',', res, ',', c, ',')
fi
rof;
list_count(res, ',')
The documentation for range() is:
Quote:
range(start, stop, step, limit) -- returns a list of numbers generated by looping over the range specified by the parameters start, stop, and step, with a maximum length of limit. The first value produced is start. Subsequent values next_v = current_v + step. The loop continues while next_v < stop assuming step is positive, otherwise while next_v > stop. An empty list is produced if start fails the test: start >= stop if step is positive. The limit sets the maximum length of the list and has a default of 1000. The parameters start, step, and limit are optional. Calling range() with one argument specifies stop. Two arguments specify start and stop. Three arguments specify start, stop, and step. Four arguments specify start, stop, step and limit.
Examples:
Code:
range(5) -> '0, 1, 2, 3, 4'
range(0, 5) -> '0, 1, 2, 3, 4'
range(-1, 5) -> '-1, 0, 1, 2, 3, 4'
range(1, 5) -> '1, 2, 3, 4'
range(5, 0, -1) -> '5, 4, 3, 2, 1'
range(1, 5, 2) -> '1, 3'
range(1, 5, 2, 5) -> '1, 3'
range(1, 5, 2, 1) -> error(limit exceeded)
|