ブロックは、1個以上のステートメントを束ね持つオブジェクトである。大括弧で1個以上のステートメントを囲むことで表記する。C言語では、ステートメントを中括弧{ }で囲み、{ }をすぐに実行するが、Smalltalk では、動けと言われるまでは実行されず、また、何度も実行することができる。
下記の例題1の準備として、下記のオブジェクトを定義しよう。
Object subclass: #Commet
instanceVariableNames: 'star'
classVariableNames: ''
poolDictionarys: ''
category: 'MyObject'
appear
star := StarMorph new.
star openInWorld
disappear
star delete
perform: term
star
position: (Point x: 10 y: 10).
Transcript show: 'pos = (10,10)';
cr.
(Delay forMilliseconds: term) wait.
star
position: (Point x: 50 y: 50).
Transcript show: 'pos = (50,50)';
cr.
(Delay forMilliseconds: term) wait.
star
position: (Point x: 100 y: 100).
Transcript show: 'pos = (100,100)';
cr.
(Delay forMilliseconds: term) wait.
実行は、Workspace 上で以下を行う。
a := Commet new (← ここを入力した後で Alt-d を押す) a appear (← ここを入力した後で Alt-d を押す) a perform: 1000 (← ここを入力した後で Alt-d を押す) a disappear (← ここを入力した後で Alt-d を押す)
下記を1行ずつ評価してみよう。
b := Commet new b appear x := [ b perform: 500. b perform: 200. b perform: 50 ] x value
(ブロックには引数を渡すことができる。)
z := [: tm | b perform: tm. b perform: (tm + 400). b perform: (tm / 2)] z value: 400 z value: 1000
プログラムの制御は、以下のメッセージを送ることで実現される。
ifTrue: の使用例
c := Commet new c appear ( 100 < 200 ) ifTrue: [ c perform: 100 ] ( 100 > 200 ) ifFalse: [ c perform: 100 ] ( 100 > 200 ) ifTrue: [ c perform: 100 ] ifFalse: [ c perform: 2000 ]
whileTrue: の使用例(whileTrue: の左側がブロックであることに注意)
i := 1. [ i < 10 ] whileTrue: [ c perform: ( i * 100 ). i := i + 1 ]
流れ星のクラス Commet を次のように改良しよう。
ヒント
小レポート作成要領
次回、演習の開始時に集めます。