[comp.lang.smalltalk] Converting strings to blocks

mjohnson@cosmos.acs.calpoly.edu (Mark S. Johnson) (06/14/91)

Is there an easy/good/correct way to convert a string into a block?
I'd like to do something like the following:

   |aString aBlock|
     aString := '[:x | ', 'x sqrt', ']'.
     aBlock := aString asBlock.
     aBlock value: 3.0
     ...

You could imagine that I read the 'x sqrt' part from the terminal at
runtime...

The code for the "asBlock" method is what I'm looking for.

Thanks in advance, Mark

-- 
Mark S. Johnson        mjohnson@stn9.me.calpoly.edu      (129.65.19.9)

randy@tigercat.den.mmc.com (Randy Stafford) (06/15/91)

In my project, we have successfully converted strings (entered by the user) to
blocks for later evaluation.  We do this by invoking the compiler on the string.
You have to be careful about what context you compile in.  An example:

aBlock := Compiler new evaluate: aString
   in: aContext
   to: aReciever
   notifying: aController
   ifFail: failBlock.

aBlock will be the compiled BlockContext that you can later send #value or
#value: to.

aString is the string you compose and want to turn into a block (i.e.
what your user enters).

aContext is the context you compile in (we use nil).  This allows the block to 
refer to temps in that context.

aReciever is expected to be an instance of some class. This allows the block to
refer to the instance variables of that instance.

aController is the controller to notify in case of a compilation error.  If you
use nil here, you better make sure that the string is bulletproof (otherwise, you
may break later when you send #value to nil, or something.).

failBlock is a block to execute in case compilation fails (we use [^nil]).


Hope this helps.


Randy Stafford
randy@tigercat.den.mmc.com