using

control structure

Syntax
using shelf indexer?
   local-scope
    


Purpose

Each shelf has a current item: the item that will be used if you refer to the shelf by its name alone, without using an indexer. By default, the current item on every shelf is the last item. The current item can be changed in any of the following ways:

  • by repeating over the shelf, in which case the current item advances on each iteration of the loop,
  • by passing a specific item of a shelf to a function as a modifiable, read-only, or write-only argument, or
  • by specifying a new current item with using and specifying an indexer.

In the following example, the default current item is output, then the current item is changed by a using qualifier and the current item is output again:

  global string animals initial { "cow"   with key "Bessie",
                                  "pig"   with key "Wilbur",
                                  "hen"   with key "Little Red",
                                  "horse" with key "Dobbin" }
  
  process
     output animals || "%n"
  
     using animals[2]
        output animals || "%n"
  
     using animals{"Little Red"}
        output animals || "%n"
  
     output animals || "%n"
          

The output of this program is:

  horse
  pig
  hen
  horse

The using qualifier is in effect only for the action that follows, which is why the final output action outputs the default current item. To make a using qualifier affect more than one action, include the actions in a do ... done block:

  process
     using animals[2]
     do
        output animals || "%n"
        set animals to "rabbit"
        output animals || "%n"
     done

You can also use using to establish an alias for a shelf. This is useful if you want to simplify a reference to a shelf that is part of a record:

  declare record metadata-type
     field string author
     field string title
     field string publisher
     field string year
     field switch in-print initial { true }
  
  process
     local metadata-type metadata
  
     using metadata:author as author
     do
        set author to "J. R. R. Tolkien"
        ; ... and so on ...
     done

If the shelf associated with an alias has multiple items, then you can index into the alias just as you would index into the shelf. The alias of a shelf has its own current item, so that if you specify an item when creating the alias, or if you subsequently change the current item with any of the methods above, that current item belongs to the alias name. The true name of the shelf has its own current item that will be used whenever the shelf is referred to by its real name.