www.delorie.com/gnu/docs/smalltalk/gst_49.html   search  
Buy GNU books!

GNU Smalltalk User's Guide

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

4.2.1 An array in Smalltalk

An array in Smalltalk is similar to an array in any other language, although the syntax may seem peculiar at first. To create an array with room for 20 elements, do(19):
   x := Array new: 20 !

The Array new: 20 creates the array; the x := part connects the name x with the object. Until you assign something else to x, you can refer to this array by the name x. Changing elements of the array is not done using the := operator; this operator is used only to bind names to objects. In fact, you never modify data structures; instead, you send a message to the object, and it will modify itself.

For instance:
   (x at: 1) printNl !
which prints:

The slots of an array are initially set to "nothing" (which Smalltalk calls nil). Let's set the first slot to the number 99:
   x at: 1 put: 99 !
and now make sure the 99 is actually there:
   (x at: 1) printNl !
which then prints out:

These examples show how to manipulate an array. They also show the standard way in which messages are passed arguments ments. In most cases, if a message takes an argument, its name will end with `:'.(20)

So when we said x at: 1 we were sending a message to whatever object was currently bound to x with an argument of 1. For an array, this results in the first slot of the array being returned.

The second operation, x at: 1 put: 99 is a message with two arguments. It tells the array to place the second argument (99) in the slot specified by the first (1). Thus, when we re-examine the first slot, it does indeed now contain 99.

There is a shorthand for describing the messages you send to objects. You just run the message names together. So we would say that our array accepts both the at: and at:put: messages.

There is quite a bit of sanity checking built into an array. The request
   6 at: 1
fails with an error; 6 is an integer, and can't be indexed. Further,
   x at: 21
fails with an error, because the array we created only has room for 20 objects.

Finally, note that the object stored in an array is just like any other object, so we can do things like:
   ((x at: 1) + 1) printNl !
which (assuming you've been typing in the examples) will print 100.

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

  webmaster     delorie software   privacy  
  Copyright 2003   by The Free Software Foundation     Updated Jun 2003