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 lowercase 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, followed by 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
Parentheses can also be used to make potentially confusing code more clear. For example, the strict left-to-right evaluation order can be confusing when applied to mathematical expressions. In the Spacewar! code snippet below, the parentheses make it more clear that the addition happens first:
newVelocity := (ai + ag) * t + velocity
To send multiple messages to the same receiver a cascade can be used to state the receiver once, followed by the cascade of messages separated by semicolons. Here is our earlier Example 1.2 code expressed with a cascade:
Transcript show: 'Hello World!'; newLine; show: 'I am Cuising'
Another example of a cascade 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
directly 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
.