select
select <iterable> <block>
Keep only the elements of an iterable for which a predicate is true, producing a new iterable.
The filter is lazy: the predicate runs on demand as the result is consumed, not all at once.
Arguments
<iterable>— a list or any iterable. A bare string is not iterable; convert it first withwords.<block>— a block taking one parameter, declared inside the braces right after{, and bound to the current element on each pass. The block is the predicate; it must yield a bool. An element is kept when the predicate yieldstrueand dropped when it yieldsfalse.
Returns
An iterable over the elements for which the predicate is true. Consume
it with each, count, first, or
another iterable consumer.
Control flow
The predicate runs per candidate as the filtered iterable is consumed.
continue drops the current candidate (same as a false
result); break ends the filtered sequence; and
return returns from the enclosing handler or def.
If the predicate yields anything other than a bool, the script stops with a run-time error.
Examples
after command (say) {
each [select [creatures $self] { <c> [ismob $c] }] { <m>
do "smile $m"
}
}
select builds an iterable of just the mobiles in the owner's room, and the
outer each smiles at each one. Note both blocks declare their
parameter (<c>, <m>) inside their own braces.
after command (say) {
let mobs [select [creatures $self] { <c> [ismob $c] }]
do "say There are [count $mobs] mobiles here."
}
Binding the result and counting it shows how the filtered iterable flows
into another consumer; in the debug world [count $mobs] evaluates to 3.
See also
slice— keep a positional range of elements rather than a filtered subset.some,every— test a predicate without producing a new iterable.each— run a block across elements for its side effects.- Blocks · Iterables and iterables · Control flow