Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 38 ยท Syntax and Messages

Variables, Scope and Pseudo-variables in Smalltalk

Learn the kinds of Smalltalk variables (temporaries, arguments, instance, class and global variables), their scope rules, and the pseudo-variables self, super, nil, true, false and thisContext.

A variable in Smalltalk is simply a name bound to an object reference. What changes from kind to kind is where the name is visible and how long its value lives. Smalltalk is dynamically typed: a variable can hold any object, and nothing is declared with a type. This lesson lists every kind of variable and every special name, and shows how closures capture them.

Smalltalk code is read-only on this site; the stand-ins are runnable JavaScript.

The kinds of variables

Kind Declared where Visible in Lifetime
Temporary | x y | at the top of a method, block or script That method or block One execution
Argument In the selector (at: index put: value) or block ([ :x | ... ]) The method/block body One execution; read-only
Instance variable In the class definition All instance methods of the class and subclasses As long as the object lives
Class variable In the class definition (classVariables) Instance and class methods of the class and subclasses As long as the class exists
Class-side instance variable In the metaclass The class (not instances) As long as the class exists
Global / Pool variable Smalltalk globals at: #Foo put: ... or a pool Everywhere As long as defined

Names of classes (OrderedCollection) and well-known globals (Transcript, Smalltalk) start with a capital letter and are global bindings.

Temporaries and arguments

SMALLTALK
average: numbers
    | total |                 "temporary"
    total := 0.
    numbers do: [ :each |     "each is a block argument"
        total := total + each ].
    ^ total / numbers size
  • A temporary starts as nil until you assign it.
  • You may not assign to numbers or each: attempts to store into an argument are a compile error.
  • Temporaries can also be declared inside a block, in which case they are fresh on each evaluation of the block.

Instance variables

An instance variable belongs to one object and is visible in every method of its class:

SMALLTALK
Object << #Counter
    slots: { #count };
    package: 'Demo'.

Counter >> increment
    count := (count ifNil: [ 0 ]) + 1.
    ^ count

Two Counter instances have separate count values. Instance variables are always private: other objects cannot read them directly and must send a message, usually an accessor. We build full classes in Defining classes and methods.

Class variables and globals

A class variable is shared by the class, all its subclasses and all their instances, which makes it like a controlled global:

SMALLTALK
Object << #IdGenerator
    slots: {};
    sharedVariables: { #Next };
    package: 'Demo'.

Globals live in the Smalltalk globals dictionary. Use them very sparingly (the Transcript is a good example); a class with class-side methods is almost always better.

Pseudo-variables

These look like variables but you cannot assign to them:

Name Meaning
self The object that received the current message
super Also the receiver, but method lookup starts in the superclass
thisContext The current stack frame (an object)
nil The only instance of UndefinedObject
true, false The Boolean objects

self is the most used. Inside any method it names the receiver, and sending a message to self runs another method on the same object (possibly overridden in a subclass). super is a way to reuse what the superclass did, covered in Inheritance, super and polymorphism.

SMALLTALK
Counter >> incrementTwice
    self increment.
    ^ self increment

thisContext gives access to the call stack and powers the debugger; ordinary programs rarely use it.

Closures capture variables

A block remembers the variables around it, even after the method that created it has returned:

SMALLTALK
makeCounter
    | n |
    n := 0.
    ^ [ n := n + 1 ]

| c |
c := self makeCounter.
c value.   "-> 1"
c value.   "-> 2"

Each call to makeCounter creates its own n, and the returned block keeps it alive. Different blocks created in the same call share the same n. A deeper look is in Blocks and closures.

Scope in the Playground

Variables you declare with | x | in a Playground belong to that window's session (the "workspace bindings"). Unknown names starting with a lowercase letter are auto-declared as such workspace variables when you run a snippet, which is handy for exploration but is not allowed inside methods. Names starting with a capital letter that do not exist raise "undeclared variable" errors.

Naming conventions

  • lowerCamelCase for variables and selectors, UpperCamelCase for classes.
  • Class variables begin with an uppercase letter, so they stand out from instance variables.
  • Use plurals for collections (customers), singular for elements (each, customer).
  • Prefix an argument with a/an when the type matters: add: anElement, at: anIndex.
JS Stand-in: closures keep their variables

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Stand-in: instance vs class variable

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which variables are visible in all instance methods of a class?

    Instance variables belong to the object and can be used by every instance method.
  2. 2. What happens if you assign to a method argument?

    Arguments cannot be assigned in Smalltalk.
  3. 3. What is the difference between self and super?

    super does not name another object; it changes where the search for the method begins.
  4. 4. What value does an unassigned temporary variable have?

    All variables start as nil until assigned.

Summary

  • Smalltalk variables hold object references and have no declared type.
  • Temporaries and arguments live for one execution (arguments are read-only); instance variables live with the object and are private; class variables are shared; globals are visible everywhere.
  • self, super, thisContext, nil, true and false are pseudo-variables you cannot assign.
  • Blocks capture the variables of their surrounding scope and keep them alive.
  • Follow the naming conventions: lowerCamelCase for variables, UpperCamelCase for classes and class variables.

Next: Defining Classes and Methods