Blocks from strings

Lex Spoon lex at cc.gatech.edu
Tue Dec 30 19:43:28 UTC 2003


Nevin Pratt <nevin at smalltalkpro.com> wrote:
> How do I programmatically create a block from a string?
> 
> The block's context would be the method that is creating the block.
> 

As a starting point, how about the simple Compiler evaluate ?

	Compiler evaluate: '[:x | x + 1]'


By the way, if your ultimate goal is to programmatically create blocks
out of chunks of code, then you can use blocks to hold the small chunks
of code and then use "holey blocks" to combine them.  For example, here
is a holey block:


	[ Transcript show: 'at start'.
	  hole  value.
	  Transcript show: 'at end ].


This holey block (not a technical term :))  has a free variable named
"hole" which can be filled in with different values.  Here is a longer
method that uses a holey block:

	createBlock:  hole1   with: hole2
		^[ Transcript show: 'at start'.
		  hole1 value.
		  Transcript show: 'in middle'.
		  hole2 value.
		  Transcript show: 'at end ].

Each call to the method will create a new block, and the holes of the
block will be filled in with different chunks of code.  hole1 and hole2
should themselves be blocks that have no arguments.

As a general warning, using strings to represent stuff tends to cause
extra difficulties compared to using objects that are richer.  For
example, you can have parse errors in strings at runtime, but the
compiler will not let you have a parse error in a holey block. 
Furthermore, if you use a debugger while a holey block is running, you
can trace where everything came from within the debugger; with strings,
the debugger will be much less helpful.

So, unless you ultimate requirement involves strings, you probably want
to use blocks instead, and you probably want to create larger blocks by
using these "holey blocks".


Just a thought.   I run into this situation a lot in the Squeak-using
class at my university.


-Lex



More information about the Squeak-dev mailing list