Package: Kernel-Methods
Class: BlockClosure
Introduction
Environment: container
Contains a sequence of operations
Defined by Mindscript expressions inside square brackets
Permits to defer the enclosed operations until a variant of #value is executed
Can have its own arguments and temporaries as a regular method but it also has the ability to use external variables
It has enclosing method or block temporaries, arguments, and receiver.
Some message needs a code block as argument. For example, #do:
needs a block to be executed for each element of the receiver.
The block is executed with the element as argument.
{1. 2. 3. 4. 5. 6. 7. 8. 9. 10} do: [:each | Console print: each, '. '].
You can also use a local variable in a block:
{1. 2. 3. 4. 5. 6. 7. 8. 9. 10} do: [:each |
| sum |
sum := 10 + each.
Console print: sum, '. '].
We can also use the block as a local variable, and execute it later by sending value
to it, or value:
with an argument.
aBlock := [ Console print: 'Hello world' ].
"Execute a block"
aBlock value.
"Execute a block with an argument"
aBlock := [:each | Console print: each, '. '].
{1. 2. 3. 4. 5. 6. 7. 8. 9. 10} do: [ :item | aBlock value: item].
Instance Method
Category: accessing
asString
- answer the code string of this block closure.numArgs
- answer the number of arguments of the receiver.
Category: controlling
whileFalse:
- Ordinarily compiled in-line, and therefore not overridable. This is in case the message is sent to other than a literal block. Evaluate the argument, aBlock, as long as the value of the receiver is false.For example:
i := 1. [ i > 10 ] whileFalse: [ Console print: i, '. '. i := i + 1 ].
whileTrue:
- Ordinarily compiled in-line, and therefore not overridable. This is in case the message is sent to other than a literal block. Evaluate the argument, aBlock, as long as the value of the receiver is true.For example:
i := 1. [ i <= 10 ] whileTrue: [ Console print: i, '. '. i := i + 1 ].
Category: evaluating
ensure:
- Evaluate a termination block after evaluating the receiver, regardless of whether the receiver's evaluation completes.onErrorDo:
- Evaluate an error handling block when there is an exception when evaluating the receiver.For example, we can use
onErrorDo:
to handle an error when divide by zero.a := 1. aBlock := [ a := a / 0 ]. aBlock onErrorDo: [ :ex | a := 0].
value
- Evaluate the receiver and answer the result.value:
- Evaluate the receiver with the given argument and answer the result.value:value:
- Evaluate the receiver with the given arguments and answer the result.value:value:value:
- Evaluate the receiver with the given arguments and answer the result.value:value:value:value:
- Evaluate the receiver with the given arguments and answer the result.
Last updated
Was this helpful?