Squeak
  links to this page:    
View this PageEdit this PageUploads to this PageHistory of this PageTop of the SwikiRecent ChangesSearch the SwikiHelp Guide
Block
Last updated at 3:08 pm UTC on 7 May 2019
Code blocks in Smalltalk are self-contained pieces of computation which can be activated by sending them the #value message or one of its variants.

A Smalltalk block is Smalltalk’s term for a closure.
Blocks are instances of class BlockContext.

Example:


Enter the two lines below in a workspace.
Then put the curser into the first line and execute it. Then the code in the second line separately.

"(1)"
aBlock := [ Transcript open; show: 'Hello World'. ]

"(2)"
aBlock value

The entity delimited by the square brackets [...] is the block. In the first line it is assigned to the variable called aBlock, but not executed. In the second line it is executed by sending it (or rather the variable representing it) the #value message.


	| s block |
	block := [MorphicProject openViewOn: nil]. "nil means a new project has to be created"
		
	s := SimpleButtonMorph new.
	s target: block.
	s actionSelector: #value.
	s label: 'New MorphicProject'.
	s openInHand



Blocks are a powerful way of parameterizing behavior (akin to procedure pointers in some other languages) and for example form the basis of some of Smalltalk's looping capabilities by providing message protocol like #whileTrue:, #whileFalse: in Boolean etc.

Blocks with arguments

A block may be defined with arguments so that values may be passed into the block at execution time. The arguments are defined by variables defined to the left of a vertical bar ("|") separating the variables from the block expressions, The variable names are preceded by a colon (":") where they are defined but the colon is not used where they are used.

aBlock := [ :msg | Transcript open; show: msg ].
aBlock value:  'Hello World'.


See also

"Simple scripts" (e.g. block as the target)

tagBeginner