Search code examples
smalltalk

How is Smalltalk's whileTrue message implemented behind the scenes?


I am trying to teach myself Smalltalk. A tutorial has this example of a while loop:

|i| 
i:=5. 
[i >0] whileTrue:[ 
 Transcript show: ((i*2) asString) ; cr. 
 i:=i-1. 
].

As I understand it, whileTrue is a message sent to a BlockClosure, telling the receiving BlockClosure to run the BlockClosure given as the argument as long as the receiver is true.

How is the whileTrue message that BlockClosure responds to implemented without a while loop construct in Smalltalk? Or is it implemented in whatever language the run-time is written in?


Solution

  • In my VisualWorks image, it's done with recursion:

    whileTrue: aBlock
    
       ^self value
          ifTrue:
          [aBlock value.
          [self value] whileTrue: [aBlock value]]
    

    However, there's also a note to the effect that the compiler will inline a #whileTrue: call if both the receiver and argument are literal blocks. So in most cases, you can also consider #whileTrue: one of the "magic" messages that looks like a message send syntactically, but is really optimized into different bytecodes under the hood.