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

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