Next: Message to string entities, Previous: Communicating entities, Up: The Message Way of Life [Index]
There are three kinds of messages in Cuis-Smalltalk:
1 factorial
the message #factorial
is sent to the
object 1
.
1 + 2
the message #+
is sent to the object
1
with the argument 2
.
2 raisedTo: 6 modulo: 10
the message consisting of the
message selector #raisedTo:modulo:
and the arguments
6
and 10
is sent to the object 2
.
Unary message selectors consist of alphanumeric characters, and start with a lower case letter.
Binary message selectors consist of one or more characters from the following set:
+ – / \ * ~ < > = @ % | & ? ,
Keyword message selectors consist of a series of alphanumeric keywords, where each keyword starts with a lower-case letter and ends with a colon.
Unary messages have the highest precedence, then binary messages, and finally keyword messages, so:
2 raisedTo: 1 + 3 factorial
⇒ 128
First we send factorial
to 3
, then we send
+ 6
to 1
, and finally we send
raisedTo: 7
to 2
.
Precedence aside, evaluation is strictly from left to right, so
1 + 2 * 3
⇒ 9
is not 7. Parentheses must be used to alter the order of evaluation:
1 + (2 * 3)
⇒ 7
However, for mathematics clarity we may want to use parenthesis even when not needed. In the Spacewar! code snippet below, the parenthesis are superfluous but improve understanding:
newVelocity ← (ai + ag) * t + velocity
In the Example 1.2, the message #show:
and #newLine
are sent to the same Transcript
entity. In such circumstance,
we can use the cascade technique to avoid this repetition. The
receiver Transcript
is written once and the sent messages are
separated by semicolon:
Transcript
show: ’Hello World!’;
newLine;
show: ’I am Cuising’
Another example from the Spacewar! game:
aShip
velocity: 0 @ 0;
morphPosition: randomCoordinate value @ randomCoordinate value
Observe the text here is formatted to ease code understanding. It is possible to write the cascade of messages in one line, but it reduces the readability of the code:
Transcript show: ’Hello World!’; newLine; show: ’I am Cuising’
The Transcript
class is frequently helpful in presenting
useful information when developing an application. An alternative to
the Ctrl-d (Do it) shortcut is Ctrl-p
(Print it), which executes the script and prints the result
direcly in the Workspace.
In the Example 2.4, we have requested no special result. Selecting the
text and typing Ctrl-p results in the default, which is to
return the object to which a message is sent, in this case the
Transcript
.
Next: Message to string entities, Previous: Communicating entities, Up: The Message Way of Life [Index]