From Newsgroup: comp.lang.awk
On 2022-03-30, Kaz Kylheku <
480-992-1380@kylheku.com> wrote:
The loop clauses are user-definable, and easily so; I'm going to have documentation on exactly how to do that.
For instance, the clause range(index, from, to) is entirely defined in
these three simple lines of code in <loop.h>, which are entirely
isolated from the complexity of loop and loop_cross:
#define __init_range(idx, from, to) (idx = (from))
#define __test_range(idx, from, to) (idx <= (to))
#define __step_range(idx, from, to) (idx++)
E.g. let's make a clause "sfixes"
that loops over string suffixes, e.g "abc" "bc" "c"
./cppawk '
#include <loop.h>
// user-defined "sfixes" loop clause
#define __init_sfixes(idx, ch, str) (idx = 1)
#define __test_sfixes(idx, ch, str) (idx <= length(str) && \
((ch = substr(str, idx)) || 1))
#define __step_sfixes(idx, ch, str) (idx++)
// use it
BEGIN {
loop (sfixes(i, sf, "abcd"))
print i, sf
}'
1 abcd
2 bcd
3 cd
4 d
Or how about controling the length of the string slices.
No, how about completely controlling the string slice and just binding
the variable:
No, let's first make a general clause "let" to set a arbitrary variable
on each iteration of the loop.
./cppawk '
#include <loop.h>
// user-defined "let" loop clause
#define __init_let(var, expr) 0
#define __test_let(var, expr) ((var = (expr)) || 1)
#define __step_let(var, expr) 0
BEGIN {
loop (range(i, 1, 10),
range_step(j, 1, 10, 2),
let(ch, substr("abcdefghijklmn", i, j)))
{
print i, j, ch
}
}
'
1 1 a
2 3 bcd
3 5 cdefg
4 7 defghij
5 9 efghijklm
How about general "first_then_until" stepping clause.
./cppawk '
#include <loop.h>
// user-defined "first_then_until" loop clause
#define __init_first_then_until(var, first, then, until) (var = (first)) #define __test_first_then_until(var, first, then, until) (!(until))
#define __step_first_then_until(var, first, then, until) (var = (then))
BEGIN {
loop (first_then_until(i, 1, i * 2, i >= 60),
first_then_until(s, "x", s s, 0))
{
print i, s
}
}
'
1 x
2 xx
4 xxxx
8 xxxxxxxx
16 xxxxxxxxxxxxxxxx
32 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
--- Synchronet 3.19c-Linux NewsLink 1.113