% $Header: c:/tads/doc/RCS/tadsref.tex 1.2 92/11/13 16:44:22 mroberts Exp Locker: mroberts $
%
% TADS Documentation, Chapter Five:  Language Reference
%
% Copyright (c) 1989 by Michael J. Roberts.  All Rights Reserved.

\chapterheader{Chapter Five}{Language Reference}{5}

This section describes in detail all of the keywords, operators,
syntactic elements, built-in functions, and special considerations of the
TADS language.\bull

\chapterbody

\majorsection{Typographical Conventions}

This section uses abstract syntax diagrams to describe the language.  In
these diagrams, several ^{typographical conventions} are used:

{\parindent=1.25in\smallskip
\item{{\it italics}} are used to represent a description of an item that
must be replaced with an actual instance of the item.
\item{[Square Brackets]} are used to indicate that the enclosed item or
items are optional.
\item{{\tt Typewriter}} text is to be used verbatim.  The same applies to
any other punctuation shown.
\smallskip}

\majorsection{Components of TADS}

The TADS development system includes a ^{compiler}, a ^{run-time system},
and several TADS source files containing basic adventure definitions.

When you write a TADS program, you use a text editor (which is not included
with TADS) to prepare a source file, then you compile the file.  The compiler
checks the entire program for syntax errors, then creates another file
containing a binary representation of your source file;
this form is more efficient to execute, so your game will require less
memory and run faster.

After you have compiled your program, you use the run-time module to
execute the game.  The run-time system contains the ^{player command
parser} and other code for user interaction.

\majorsection{Input File Format}

The TADS ^{compiler} accepts standard ^{ASCII} text files as input.
The compiler
considers any amount of ^{whitespace} to be the same as a single space; spaces,
tabs, and newlines all count as whitespace.  Whitespace can occur between
any two syntactic elements, but need only appear between two identifiers
or keywords that have no other intervening punctuation.  The compiler knows
that punctuation is never part of a keyword or identifier, and can manage to
break apart punctuation when it's all run together without spaces.  For
readability, liberal use of whitespace is recommended.

\minorsection{Including Other Files}

The {\tt ^{\#include}}
directive allows one file to insert the contents of another:

{\example
    \#include "file.t"
    \#include <file.t>
\medskip}

Here, {\tt file.t}
is the name of an operating system file to be included.  An
included file can include another, and so forth, down to ten levels of nested
files.  Note that the pound sign, {\tt \#},
must be in the first column of the line;
no leading spaces are allowed.  The include file {\tt adv.t}\
is normally included
at the start of a game file to define the many items that are needed in a
normal adventure.  These definitions are quite general, but specific games
might modify them to customize the game.

Note that when the filename is enclosed in double quotes, the compiler
searches for the file first in the current directory, then in the
directories in the ^{include path} (as set with the {\tt -i} compiler
switch on most operating systems).  When the filename is enclosed in
angle brackets, the compiler searches only in the directories in the
include path---the current directory is {\it not} searched.
Generally, a system include
file (such as {\tt ^{adv.t}})
should be enclosed in ^{angle brackets}, while your files
should be in the current directory and enclosed in ^{double quotes}.

\minorsection{Multiple Inclusions of the Same File}

^^{Multiple inclusions of the same file}
The TADS compiler automatically keeps track of each file you have included,
and ignores redundant {\tt \#include} directives.  Note that this feature is
based on the filename as specified in your program; if you refer to the same
file by different names (for example, by specifying a path on one inclusion,
but using angle brackets to let TADS find the file on the second), the
compiler will not be able to identify the duplicate file, and will include
it twice, resulting in countless unnecessary errors.  For this reason,
you are encouraged to use angle brackets to specify include files, rather
than using specific paths in your source file.  Doing so will help ensure that
your source files are portable to different computers, as well, since
each operating system uses its own conventions for specifying file paths.

Note that the include files that make up a ^{pre-compiled} binary file, loaded
with the compiler's {\tt -l} option, are recorded in the binary file.  Thus,
there is no need for you to remove the {\tt \#include} directive in your
source file just because you are using the pre-compiled version of that
include file.  For more information on using pre-compiled include files,
see the section on using the compiler.

\minorsection{Comments}

Outside of a quoted string, two consecutive slashes, {\tt ^{//}},
indicate that the
rest of the line is a comment.  Everything up to the next newline is ignored.

Alternatively, C-style ^{comments} can be used; these
start with {\tt ^{/*}} and end with {\tt ^{*/}}; this
type of comment can span multiple lines.

Examples:

{\example
    // This line is a comment.

    /*
     This is a comment
     which goes across
     several lines.
    */
}

\majorsection{Identifiers}


^{Identifiers} must start with a letter (upper or lower case), and may contain
letters, numbers, dollar signs, and underscores.  Identifiers can be up to 39
characters long.  Upper and lower case letters are distinct.

\minorsection{Scope of Identifiers}


All objects and functions are named by global identifiers.  No identifier
may be used to identify different things; that is, no two objects can have the
same name, an identifier naming a function can't also be used for an object,
and so forth.

Property names are also global identifiers.  A name used for a property
can't be used for a function or object, or vice versa.  However, unlike
functions and objects, the same property name can be used in many different
objects.  Since a property name is never used alone, but always in
conjunction with an object, the TADS compiler is able to determine which
object's property is being referenced even if the same name is used in
many objects.

Function ^{arguments} and ^{local}
variables are visible only in the function in
which they appear.  It is permissible to re-use a global identifier as a
function argument or local variable, in which case the variable supersedes
the global meaning within the function.  However, this is discouraged, as it
can be a bit confusing.

\majorsection{Object Definitions}


A basic ^{object} definition has the form:

{\example
    {\it identifer}:  object {\it [property-list]} ;
}

This defines an object which has no superclass.  An object can be defined
as having a superclass with the alternative form of object definition:

{\example
    {\it identifier}:  {\it class-name [}, {\it class-name [$\ldots$]]}  %
      {\it [property-list]} ;
}

Here, the {\it class-name}
is an identifier which is defined elsewhere in the program
as an object or ^{class} (either with or without a ^{superclass}),
and is the new object's
superclass; if more than one superclass is present, a comma separates
each superclass in the list.  The new object named by {\it identifier}
inherits all the ^{properties}
of the superclass or superclasses. 
If a property in the optional {\it property-list}
is also in the
property list of the superclass (or its superclass, and so forth), the
new property overrides the inherited one.

If a property is ^{inherited} from more than one of its superclasses (and is
not ^{overridden} in the object's own property list),
the property is inherited from the
superclass that appears earliest in the list.  For example, suppose you
define an object like this:

{\example
    \object{vase: container, fixeditem}
    \endobj    
}

If both {\tt container} and {\tt fixeditem} define a ^{method} named {\tt
m1}, and {\tt vase} itself doesn't define an {\tt m1} method, then {\tt m1}
is inherited from {\tt container}, because it appears earlier in the
superclass list than {\tt fixeditem}.

There is a more complicated case that can occur, but it is very unusual.
You will probably never encounter this, so skip this section if you
find it confusing.  Suppose that in the example above, both {\tt container}
and {\tt fixeditem} have the superclass {\tt item}, and that {\tt item}
and {\tt fixeditem} define method {\tt m2}, and that neither {\tt container}
nor {\tt vase} define {\tt m2}.  Now, since {\tt container} inherits {\tt m2}
from {\tt item}, it might seem that {\tt vase} should inherit {\tt m2} from
{\tt container} and thus from {\tt item}.  However, this is not the case;
since the {\tt m2} defined in {\tt fixeditem} overrides the one defined in
{\tt item}, {\tt vase} inherits the {\tt m2} from {\tt fixeditem} rather than
the one from {\tt item}.  Hence, the rule, fully stated, is:  the inherited
property in the case of multiple inheritance is that property of the earliest
(leftmost) superclass in the object's superclass list that is not overridden
by a subsequent superclass.

\minorsection{Property Lists}


A property list takes on this form:

{\example
    {\it property-definition} {\it [property-list]}
}

(This is a formal way of saying that you can string together any number of
property definitions in a property list, one after the other.)  A property
definition looks like this:

{\example
    {\it identifier} = {\it data-item}
}

Note that no ^{semicolon} comes after the property definition. A semicolon
terminates the entire object definition, not individual property definitions.

\minorsection{Property Data Items}



A data item can be a number, a double-quoted string, a single-quoted string,
a list, an object, {\tt nil}, or {\tt true}.

\minorsection{Numbers}


A ^{number} is just a string of digits.  The default base is decimal; you can
also enter ^{octal} and ^{hexadecimal}
numbers.  An octal number simply starts with
a leading zero, so {\tt 035}
is an octal number having the decimal value 29.  A
hexadecimal number starts with {\tt 0x}, as in {\tt 0x3a9}.

Numbers can vary from -2147483647 to 2147483647 (decimal), inclusive.
Only integers are allowed; numbers cannot have a decimal point or a
fractional part.

\minorsection{Double-quoted Strings}


A ^{double-quoted string}
is an arbitrary string of characters enclosed in double
quotation marks, such as,

{\example
    "This is a double-quoted string."
\smallskip}

Stretches of ^{whitespace}
in such strings are compressed to single spaces.  This includes newlines;
double-quoted strings can go on past the end of a line, and keep going for
several lines.  For example, this is perfectly legal:

{\example
    "This is a string
    that goes on for
\bigskip
    several lines."
\smallskip}

Note that TADS converts all of that blank space, including the blank lines,
down to a single space between each word. Thus, you can enter your text
without having to worry about formatting it; TADS will do all the work
of filling up each output line when your program runs.

Sometimes, you will want to format your output in a specific way, overriding
the standard output formatting. Since TADS converts all whitespace in your
strings (including newlines) to spaces, you have to specify any
special formatting you want explicitly.  TADS provides several special
character sequences you can use to obtain these effects.

{\advance\leftskip2in
\def\charitem#1{\medskip\indent\llap{\hbox to 1in{{\tt #1}\hfill}}}

\charitem{\char`\\t}^{Tab} to the next stop.  Tab stops are every four spaces.
This is useful if you want stretches of blank space within a line.

\charitem{\char`\\n}A ^{newline}.  Ends the current line, and skips to a
new one.  Note that repeating this sequence has no effect, since the
output formatter ignores redundant {\tt \char`\\n} sequences; this is
normally convenient, because it means you don't have to worry about several
newline sequences being displayed by different objects filling the
display with unwanted blank lines.
If you want to force one
or more blank lines, use {\tt \char`\\b}.

\charitem{\char`\\b}Ends the current line, and then outputs a blank line.

\charitem{\char`\\"}A double quote.

\charitem{\char`\\\char`\\}A backslash.

\charitem{\char`\\<}A left angle bracket.  This is not required to produce
a single angle bracket (although it will do so), but you will need to use
this on second and subsequent angle brackets in a stream of contiguous
angle brackets, to prevent TADS from thinking you want to embed an expression
in your string (see below).  Hence, if you want to display {\tt <<<<<},
you will have to type this in your program:
{\tt "<\char`\\<\char`\\<\char`\\<\char`\\<"}.

\charitem{\char`\\ \char`\^}(That is, a backslash followed by a circumflex
or ``up arrow" or ``hat," entered with the shifted ``6" key on most keyboards.)
This sequence causes the next character in the output to be capitalized.
This sequence is generally used just before invoking a function or method
that will display text that will be at the start of a sentence.  By using
this sequence prior to the text, you ensure that the first letter of the
sentence is capitalized, even if the function or method displaying the text
doesn't know it should be capitalized.  For example:  {\tt "\char`\\
\char`\^ << obj.adesc >> is sitting on the table."}  Note that the {\tt caps()}
built-in function has the same effect.

\charitem{\char`\\{\it space}}(That is, a backslash followed by a space.)
A quoted space. This is useful in certain cases to achieve special
formatting effects, because it overrides the output formatter's suppression
of multiple spaces, and it also suppresses the double-space that follows
punctuation marks such as periods.  For example, if you want to print
someone's name with a middle initial, you don't want two spaces after the
initial; you would thus enter: {\tt "Michael J.\char`\\{} Roberts"}.

\charitem{\char`\\(}Begin highlighting.  Text after the {\tt \char`\\(}
is displayed with a special attribute, which varies by system; on some
machines it will appear in a different color than ordinary text, while
on others it may appear with a different typeface.  On some systems it
may have no effect.  This is intended to be used for emphasizing text
the same way that boldface or italics would emphasize text in a book.
Note that highlighting does not ``nest''; that is, if a {\tt \char`\\(}
sequence occurs while highlighting is already active, the second sequence
has no additional effect.

\charitem{\char`\\)}End highlighting.  Text after the {\tt \char`\\)}
without the special highlighting attribute.  Note that a single
{\tt \char`\\)} sequence turns off highlighting, no matter how many
{\tt \char`\\(} sequences preceded it.

\medskip}

There is no specific limit on the length of a double-quote string,
although the compiler may impose some limits depending on the context
in which the string appears.

A double-quoted string is always displayed whenever evaluated.  When a
double-quoted
string appears in code, executing that code results in displaying the
string.  Likewise, when a property has a double-quoted string as its value,
the string is displayed whenever the property is evaluated.

\minorsection{Embedding Expressions in Strings}

TADS has a convenient feature which allows you to ^{embed expressions} in
strings, without actually stopping the string.  Any time TADS encounters
two consecutive left ^{angle brackets} in a string, it will momentarily stop
the string, and evaluate what comes after the angle brackets as an expression
whose value is to be displayed.
The expression ends, and the string resumes, when two right angle brackets are
encountered.  This makes property definitions that need to look up another
property very convenient to define; for example,

{\example
    itsHere = "<< self.thedesc >> is here."
\smallskip}

The statement above is equivalent to this more verbose version:

{\example
    itsHere =
    \lb
         self.thedesc; " is here.";
    \rb
\smallskip}

An embedded expression can evaluate to a number, a single-quoted string, or
a double-quoted string.  Other datatypes are not allowed.  A string may have
any number of embedded expressions within it.  An embedded expression may
only contain an expression; statements (such as {\tt if}) are not allowed,
and semicolons may {\it not} be used to separate multiple expressions---use
commas instead.

This feature has certain limitations.  It is illegal to use a string
in an embedded expression which itself has an embedded expression.
This feature can be used only in double-quoted strings;
single-quoted strings cannot contain embedded expressions.

Because some game authors may wish to use two or more consecutive
left angle brackets in their strings, the special sequence `{\tt \char`\\<}'
is provided.  See the section on special character sequences, above, for
more information.

\minorsection{Single-quoted Strings}

^{Single-quoted strings} are essentially the same as double-quoted strings in
appearance, except, of course, that they are enclosed in single quote marks.
The sequence {\tt \char`\\'}
is available to produce a single quote in the string itself.

Single-quoted strings do not display when evaluated; instead, they are treated
as values.  Certain built-in functions are available to manipulate these
strings, such as {\tt say}, which displays such a string value.

Note also that all ^{vocabulary}
words appear as single-quoted strings (or lists
of single-quoted strings).

\minorsection{Lists}


A ^{list} is an aggregate of other data items.  It is entered as a set of data
items enclosed in ^{square brackets} (note that these square brackets are the
actual punctutation, not indicators of optionality):

{\example
    [ {\it data-list} ]
}

A {\it data-list} can be nothing at all, in which case the list
is empty, as in

{\example
    []
}

Or, it can be one or more data items (numbers, strings, objects, lists).
Generally, it is only useful to
construct lists with the same datatype for all members, but this is not
required by the language.

Examples of lists:

{\example
    [ 1 2 3 ]
    [ 'hello' 'goodbye' ]
    [ [1 2 3] [4 5 6] [7 8 9] ]
    [ vase goldSkull pedestal ]
}

List elements need not be constants, unless the entire list needs to
be a constant.  For example, a list used as a property value must be
a constant, so all of the elements must be constants (hence, local
variables and non-constant expressions cannot be used).  However, a
list used in code, such as a list assigned to a local variable, can
contain non-constant expressions within the list elements.  For example,
the following function dynamically constructs a list from three
expressions:

{\example
f: function(x, y, z)
\lb
    return([x+1 y+1 z+1]);
\rb
}

The non-constant list elements are legal because the list construction
appears in code.  Note that the routine above has the same effect as
this code:

{\example
f: function(x, y, z)
\lb
    return((([] + (x+1)) + (y+1)) + (z+1));
\rb
}

The second example starts with an empty list, then adds an element
whose value is {\tt (x+1)}, then adds a second element whose value is
{\tt (y+1)}, and so on.  The two examples construct exactly the same
list.  However, you should use the first construct where possible,
because it is much more efficient:  the first example constructs
only a single list, whereas the second must construct {\it four}
lists, one at a time.  The first example is faster and consumes
less memory at execution time.

\minorsection{nil and true}


Two special datatypes, {\tt ^{nil}} and {\tt ^{true}},
are pre-defined.  These are generally used as ``truth
values"; {\tt nil} means false and {\tt true} means true.  For example,
{\tt 1 > 3} evaluates to {\tt nil}, whereas {\tt 1 < 3} is {\tt true}.
In addition, {\tt nil} means the absence of
a value; taking the {\tt car} of an empty list returns {\tt nil}, as does
evaluating a property of an object when the property is neither defined
nor inherited by the object.

For truth values, you should use {\tt nil} and {\tt true} rather than
numeric equivalents, since {\tt nil} and {\tt true} provide much more explicit
self-documentation of your program.

\minorsection{Expressions}

A property definition can contain an ^{expression} rather than a simple
constant.  When a property value is an expression, the expression must be
enclosed in parentheses.  The expression is evaluated each time the property
is evaluated.  An example of using an expression for a property value:

{\example
    \object{exprObj: object}
        x = 1
	y = 2
	z = (self.x + self.y)
    \endobj
}

Whenever {\tt exprObj.z} is evaluated, the sum of the current
values of {\tt exprObj.y} and {\tt exprObj.z} is returned.

Note that a property defined in this manner can take parameters, just like
methods (described below).  For example:

{\example
    \object{exprObj2: object}
        w(a, b) = (a * b)
    \endobj
}

When {\tt exprObj2.w} is evaluated, it requires two parameters, which are
multiplied together to give the value of the property.  For example,
evaluating {\tt exprObj2.w(3, 4)} produces a value of {\tt 12}.

Note that the property {\tt z} above could have been written without
the ``{\tt self.}'' prefix on {\tt x} and {\tt y}:

{\example
    z = (x + y)
}

This is because properties, if used without an object name, are
assumed to belong to the current {\tt self} object.

\minorsection{Methods}

Code can be used in a property definition just like any other datatype;
when you associate code with an object, the code is called a {\sl ^{method}}.  
When
the method is evaluated, the code is executed; the return value is the value
of the method, but often it is useful for the code to produce side
effects as well.

Method code is enclosed in ^{braces}, {\tt $\{$} and {\tt $\}$}.
Anything valid in a ^{function} may appear
in code associated with a method.  The method may have ^{local}
variables, and it can receive ^{arguments}.  If the method has arguments, the
argument list (which is identical to a function's argument list) appears
after the method name.  For example:

{\example
    \object{obj1: object}
        f(x) = 
	\lb
	    return(x + 1);
	\rb
    \endobj
}

When such a method is evaluated, the argument list is specified after the
method name, as in:

{\example
    f1: function
    \lb
        say(obj1.f(123));
    \rb
}


\majorsection{Functions}


A ^{function} definition has this form:

{\example
    {\it identifier}:  function {\it [} ( {\it argument-list} ) {\it ]} 
    \lb
        {\it function-body}
    \rb
}

The {\it argument-list} is optional; functions need not take arguments. If the
function does take one or more ^{arguments}, the list looks like this:

{\example
    {\it identifier [}, {\it argument-list ]}
}

The identifiers may be used just like local variables within the function.

The punctuation in the above syntactic description may be a little much, so
an example might be helpful:

{\example
  addlist: function(list)   \hfill    // add up the numbers in the list
  \lb
    local sum, count, i;
    
    i := 1;               \hfill      // index the first item in the list
    sum := 0;             \hfill      // initialize the sum to zero
    count := length(list); \hfill   // get the number of items in the list
    while (i < count)    \hfill      // as long as there's more to do...
    \lb
        sum := sum + list[i]; \hfill  // add next element
	i := i + 1;           \hfill  // go on to the next list element
    \rb
    return(sum);
  \rb
}

\minorsection{Functions with Variable Argument Lists}

It is possible to define a function that takes a variable number
of arguments.  In the function definition, you can specify a minimum
number of arguments that are always passed to the function (which can
be no arguments at all, if you wish), and then specify that more
arguments can optionally follow.  This is done with the ``^{ellipsis}''
token, ``{\tt ^{...}}'', as the final ``argument'' in the function's
argument list.  For example, to define a function that takes any
number of arguments:
^^{variable argument lists} ^^{varargs functions}

{\example
f: function(...)
\lb
\rb
}

To define a function that always takes at least one argument, but
could take additional arguments:

{\example
g: function(fmt, ...)
\lb
\rb
}

In a function taking a variable number of arguments, you can determine
how many arguments were actually passed to the function by inspecting
the pseudo-variable {\tt ^{argcount}}.  This pseudo-variable's value is
simply the number of arguments to the current function.

To retrieve an argument, use the {\tt ^{getarg}({\it argnum})} built-in
function.  The argument {\it argnum} is the number of the argument
you want to retrieve; {\tt getarg(1)} returns the first argument,
{\tt getarg(2)} returns the second, and so forth.  Note that in a
function which has some explicit arguments, followed by an ellipsis,
{\tt getarg(1)} still returns the first argument, even though it has
a name in the argument list.  For example, in the function {\tt g}
above, {\tt getarg(1)} returns the value of the argument {\tt fmt}.

Another built-in function, {\tt ^{datatype}({\it value})}, can be used
to determine the datatype of an argument.  See the description of the
{\tt datatype} function later in this chapter for more information.

As an example, the function below displays any number of values.

{\example
displist: function(...)
\lb
    local i;
    for (i := 1 ; i <= argcount ; i++)
    \lb
        say(getarg(i));
        " ";
    \rb
    "\char`\\n";
\rb
}

\minorsection{Forward-Declaration of Functions}

An alternative form of the {\tt function} statement allows you to
^{forward-declare} a name as a function, without actually defining the
function.  The format of a forward declaration is:

{\example
    {\it identifier}: function;
\medskip}

Note that this does {\it not} define the function; it merely tells
the compiler that a function definition for the
specified {\it identifier} will appear later in the file.  This reserves
the {\it identifier} for use as a function name, and prevents the compiler
from assuming the {\it identifier} refers to an object.

Forward declarations are not necessary except where {\tt setdaemon()} and
the like will be used.  When a function is actually called, the syntax of
the call tells TADS that the name refers to a function even when TADS hasn't
seen the function definition yet.  In {\tt setdaemon()} and similar calls,
though, no special syntax is present to tell TADS what the identifier
refers to, so the compiler assumes it will refer to an object.

\majorsection{Writing Code}

In this section we cover the details of the language that goes
inside functions
and methods.  Function and method code consists of a series of ^{statements};
the statements are executed sequentially in the order they appear in the
source program.  The following pages provide details about the statements
that may be used.

Each statement in TADS code is terminated with a semicolon.

\minorsection{local}

At the start of a function or property definition, you can define ^{local}
variables for the current code block.  This is done with a statement such as
this:

{\example
    local {\it identifier-list} ;
}

The {\it identifier-list} has the form:

{\example
    {\it identifier [ initializer ] [}, {\it identifier-list ]}
}

An {\it initializer}, which is optional, has the form:

{\example
    := {\it expression}
}

where the {\it expression} is any valid expression, which can contain
arguments to the function or method, as well as any local variables
defined prior to the local variable being initialized with the expression.
The expression is evaluated, and the resulting value is assigned to
the local variable prior to evaluating the next initializer, if any,
and prior to executing the first statement after the {\tt local}
declaration.  Local variables with initializers and local variables
without initializers can be freely intermixed in a single statement;
any local variables without initailizers are automatically set to
{\tt nil} by the run-time system.

The identifiers defined in this fashion are visible only inside the function
in which the {\tt local} statement appears.  Furthermore, the local statement
supersedes any global meaning of the identifiers within the function.

A {\tt local} statement can occur in any block (that is, any statements
grouped together with braces), and a single block can have multiple
{\tt local} statements; all {\tt local} statements in a block must
precede the first executable statement of the block (that is, the
only thing that can occur before a {\tt local} statement is another
{\tt local} statement.

An example of declaring local variables, using multiple {\tt local}
statements, and using initializers is below.

{\example
    f: function(a, b)
    \lb
        local i, j; \hfill /* no initializers */
    local k := 1, m, n := 2; \hfill /* some with initializers, some without */
   local q := 5*k, r := m + q; \hfill /* OK to use q after it's initialized */

        for (i := 1 ; i < q ; i++)
        \lb
            local x, y;  \hfill /* locals can be at start of any block */
            say(i);
        \rb
    \rb
}

\minorsection{Expressions}

TADS ^{expressions} are entered in algebraic notation.  Operators have
different meanings on different datatypes.  The basic list follows.

\medskip

{\advance\leftskip2in
\def\opitem#1{\medskip\indent\llap{\hbox to 1in{{\tt #1}\hfill}}}

\newdimen\rulewidth \rulewidth=\hsize
\advance\rulewidth by-1in
\def\oprule{\bigskip\moveright 1in\hbox to\rulewidth{%
\vrule height 0.4pt width\rulewidth}}

\opitem{^{\&}}Takes ``address'' of a function or property. The {\tt \&}
operator {\it must} be immediately followed by the name of a property
or the name of a function.  You can assign this value to a local variable
or a property, or you can pass it to a function or method.  The address
value can then be used to call the function or property.  See ``Indirect
Function and Method Calls'' later in this chapter.
(Note:  older versions of TADS used the
{\tt \#} operator to take the address of a function.  This operator is
still understood by the system, but we recommend that you use {\tt \&}
in new code instead.)^^{\#}

\oprule

\opitem{^{.}}Takes a ^{property} of an ^{object}.  On the left of the dot
is an expression that evaluates to an object, and on the right is a
property name.  If the property is a method that requires arguments, these
arguments are listed in parentheses after the property name, just as with
function arguments.  A local variable or an expression enclosed in
parentheses may appear on the right hand side; the local or expression
must evaluate to a property pointer.

\opitem{^{[]}}^{List indexing}; 
applied to the right side of a list-valued
expression.  An expression which evaluates to a number must appear between
the square brackets.  If the index (i.e., the value between the square
brackets) is {\it n}, the {\it n}th element of the list is returned by this
operator.  The first element in the list is number 1.  For example,
{\tt ['one' 'two' 'three'][1+1]} evaluates to the string {\tt 'two'}.  Note
that a run-time error results if {\it n} is outside the bounds of the list;
that is, {\it n} is less than 1 or greater than the number of elements in
the list (as returned by the {\tt length()} built-in function).

\opitem{^{++}}^{Increment}; adds one to a numeric variable or property.
The expression to which {\tt ++} is applied must be suitable for
assignment (i.e., it must be something that you can use on the
left-hand side of the assignment operator, ``{\tt :=}'').  The
{\tt ++} operator can be either a prefix or postfix operator---that
is, it can be placed either before or after its operand.  If it's
placed before the operand, as in {\tt ++i}, the operand is incremented,
and the value of the expression is the value of the operand {\it after}
the increment.  If it's placed after the operand, as in {\tt i++}, the
value of the expression is the value of the operand {\it before} the
increment.  So, if the variable {\tt i} has the value {\tt 3},
{\tt ++i} has the value {\tt 4}, while {\tt i++} has the value {\tt 3}.
Think about it by reading the expression left-to-right, and noting
that the value of the expression is the value of {\tt i} {\it when
you read it}, and the increment is applied when you read the {\tt ++}
operator.  So, with {\tt ++i}, you first read the increment operator,
which adds 1 to {\tt i}, then you note the value of {\tt i}, which
by now is {\tt 4}.  With {\tt i++}, you first read {\tt i} and note
its value, which is still {\tt 3}, then you see the {\tt ++} operator,
leaving {\tt 4} in {\tt i}.

\opitem{^{--}}^{Decrement}; subtracts one from a numeric variable
or property.  This acts exactly like the {\tt ++} operator, except that
it decrements its operand rather than incrementing it.

\oprule

\opitem{^{not}}^{Logical negation}.  Turns
{\tt ^{true}} into {\tt ^{nil}} and vice versa.  This operator can only
be applied to the values {\tt true} and {\tt nil}.

\opitem{^{-}}{Arithmetic negation.}  As a unary prefix operator (that is,
an operator that precedes its single operand), the minus sign negates the
number following it.

\oprule

\opitem{^{*}}Numeric ^{multiplication}.  Multiplies the numbers on either
side of the asterisk together.

\opitem{^{/}}Numeric ^{division}.  The number on the left of the slash
is divided by the number on the right.  Note that TADS numbers are all
integers; the remainder of the division is discarded.  Hence, {\tt 7/2}
has a value of {\tt 3}.

\oprule

\opitem{^{+}}^{Adds} numbers, ^{concatenates lists}, 
^{concatenates strings}.
If both the left and right are
numbers, the result is numeric addition.  If one or the other is
a list, but not both, the non-list is added as the last element
of the list.  If both operands are lists, the items from the list
on the right side are appended to the list on the left; for example,
{\tt [1 2 3] + [4 5]} yields the list {\tt [1 2 3 4 5]}.
If both are strings, the right
string is concatenated to the left string. Other datatypes are
illegal.

\opitem{^{-}}^{Subtracts} numbers, removes items from lists.  If both
operands are numbers, the right operand is subtracted from the left.
If the left element is a list, the right item is removed from the
list if it appears in the list on the left
(nothing happens if not); if the right item is also a list, each
element from the right list that appears in the left list is removed
from the left list.  Other datatypes are illegal.

\oprule

\opitem{^{=}}Equality.  The datatypes on either side must be the same, but
can't be lists.  One exception:  anything can be compared for equality
to {\tt nil}.  Evaluates to {\tt true}
if the items are the same, {\tt nil} otherwise.

\opitem{^{<>}}Inequality.  True if the operands on both sides are not
the same (although the datatype of each operand must be the same).

\opitem{^{>}}Greater than.  Like the other ^{comparison operators},
this may only
be applied to numbers and strings. Evaluates to {\tt true} or {\tt nil}.
Note that, when applied to strings, the comparison is based on the
collation sequence of the character set of the computer you are using,
such as ASCII.

\opitem{^{<}}Less than.

\opitem{^{>=}}Greater than or equal to.

\opitem{^{<=}}Less than or equal to.

\oprule

\opitem{^{and}}Logical product:  both the left and right sides must
be {\tt true}, in which case the value is {\tt true}; otherwise, the value is
{\tt nil}.  Note that if the left operand is {\tt nil}, the right operand
is not evaluated at all, since the value of the expression will be {\tt nil}
regardless of the value of the right operand.

\oprule

\opitem{^{or}}Logical sum:  one or the other of the left or right
operators must be {\tt true} for the value to be {\tt true}; otherwise the
value is {\tt nil}.  Note that if the left operand is {\tt true}, the right
operand is not evaluated at all, since the value of the expression will
be {\tt true} regardless of the value of the right operand.

\oprule
	    
\opitem{^{? :}}^{Conditional.} This is a {\it tertiary} operator; that is,
it takes three operands, of the form {\it cond} {\tt ?} {\it true-expr}
{\tt :} {\it false-expr}.  First, the {\it cond} is evaluated; if it evaluates
to {\tt true} or a non-zero number, then the {\it true-expr} is evaluated,
and its value is the value of the entire conditional expression.  If the
{\it cond} is false, the {\it false-expr} is evaluated, and its value is
the value of the entire expression.  Note that either {\it true-expr}
or {\it false-expr} is evaluated---not both.  This allows you to use this
operator when the expressions have side effects, such as displaying strings.

\oprule

\opitem{^{:=}}^{Assignment}.  The variable or property on the left of the 
operator is assigned the value on the right side.  This is the lowest
priority operator, and operates right to left, unlike the other
operators.  Hence, {\tt a := b := 3} assigns the value {\tt 3} to {\tt b},
then to {\tt a}.  Note that an assignment is an expression, which returns
the assigned value; hence, the value of {\tt (a := 3) + 4} is {\tt 7},
with the side effect that the variable {\tt a} has been set to {\tt 3}.

\opitem{^{+=}}^{Add and assign}.  This is simply short-hand notation.
The expression {\tt a += b} has exactly the same effect as the
expression {\tt a := a + b}, except that the {\tt +=} operator makes
the expression easier to write.  The value of the expression is
{\tt a + b}, which is the same as the value of {\tt a} after
the assignment.

\opitem{^{-=}}^{Subtract and assign}.  This is short-hand notation.
The expression {\tt a -= b} has the same effect as {\tt a := a - b}.

\opitem{^{*=}}^{Multiply and assign}.  The expression
{\tt a *= b} has the same effect as {\tt a := a * b}.

\opitem{^{/=}}^{Divide and assign}.  The expression
{\tt a /= b} has the same effect as {\tt a := a / b}.

\oprule

\opitem{^{,}}^{Conjunction}.  The comma operator simply allows you to
start a new expression within an expression.  On the left hand side is
an expression, and on the right hand side is another expression.  The
two expressions are independent; the comma operator performs no
computation on either expression.  The value of a pair of expressions
separated by a comma is the value of the second (right-hand) expression.
The comma operator is useful mostly in contexts where an expression
is required, but you wish to evaluate several otherwise independent
expressions for their side effects.  For example, in the initialization
portion of a {\tt for} statement, you often wish to initialize several
variables; you can do this by separating the initializations with commas.
See the description {\tt ^{for}} statement later in this chapter.
{\it Note:} the comma operator is different from a comma that appears
in a function's or method's argument list.  In the argument list,
the comma simply separates different expressions that are the
arguments; in a normal expression, however, the comma separates
parts of the same expression.

\medskip}


The operators are shown above in their ^{order of evaluation}, from first
to last.  Hence, conjunctions are done last, after all higher-precedence
operators have been evaluated.  Note that there are some groups of operators
in the list above; for example, all of the comparison operators are grouped
together.  This indicates that these operators have the same precedence.
Operators of the same precedence associate left to right; for example,
{\tt 3-4+5} is evaluated as {\tt (3-4)+5}.  The exception is the
assignment operator, which groups right to left; that is, in the
expression {\tt a := b := 2}, {\tt b} is first set to {\tt 2}, then
{\tt a} is set to {\tt b}.

You can use parentheses to force a different order of evaluation of your
expression.

\minorsection{Assignments}


An ^{assignment} is not a special type of statement; it is merely an
expression which uses an assignment operator:

{\example
    {\it item} ^{:=} {\it expression};
}

The {\it item} is a local variable, a list element, or an object's property.
When assigning to a property of an object,
the object reference may itself be an expression.  Likewise, when assigning
to a list element, the list and index may both be expressions.  Note, however,
that lists cannot be expanded by assigning to an element past the end of the
list; the index must refer to an existing member of the list to be replaced.
A few examples of assignments:

{\example
a: function(b, c)
\lb
    local d, e, lst;
    
    d := b + c;            \hfill     // assign a local variable
    obj3.prop1 := 20;      \hfill     // assign obj3's property prop1
    e := obj3;             \hfill     // assign an object to a local variable
    e.prop1 := obj2;  \hfill    // assign obj3's property prop1 the object obj2
    e.prop1.prop2 := 20;\hfill   // assign obj2's property prop2 the number 20
    fun1(3).prop3 := 1 + d;\hfill// assign prop3 of the object returned by fun1
    
    lst := [1 2 3 4 5];     \hfill  // set up a local variable with a list
    lst[3] := 9;            \hfill  // lst is now [1 2 9 4 5]
    lst[5] := 10;           \hfill  // and it's [1 2 9 4 10] now
    /* lst[6] := 7 would be illegal - the list is only 5 elements long */
\rb
}


\minorsection{Function Calls}

A ^{function call} is simply an expression involving a call to a function:

{\example
    {\it function-name}( {\it [ argument-list ] } );
}

The {\it function-name}
is the name of a ^{function} defined elsewhere.  The ^{argument}
list, if provided, is passed to the function for its parameters.  (Naturally,
the arguments passed to a function should match in number those defined in
the function's definition.)  Each parameter can be an arbitrary expression,
and the individual arguments are separated by commas.

Whether there's an argument list or not, the parentheses are required; they
tell the compiler that you wish to call the function.  (You may wonder where
you would ever want to use a function's name other than when calling the
function.  A few special built-in functions, such as {\tt setdaemon}, which
will be discussed in detail later, allow you to specify a function that is
to be called eventually, but not right away.  In these cases, you need to be
able to refer to a function without actually calling it.  In these cases,
you use the function's name without parentheses.)

If the function returns a value, the value is discarded in this form of the
call.  A function called in this manner is invoked for its side effects
rather than its return value.

An example:

{\example
    showlist(a+100, 'The list is: ', list1);
}


\minorsection{Indirect Function and Method Calls}

You can call a function or method ``indirectly''; that is, you can use
a pointer to a function or method to call the function or method.  This
can sometimes be useful in setting up a general routine which calls
other routines based on parameters passed into it.
^^{indirect function calls}
^^{indirect method calls}

To call a function with a ^{function pointer}, simply use an expression
yielding a function pointer, within parentheses, where you'd normally
use a function name.  For example:

{\example
g: function(a, b, c)
\lb
    return(a + b + c);
\rb
\vskip 12pt
f: function
\lb
    local fptr, x;
    fptr := \&g;      \hfill /* get address of function g */
    x := (fptr)(1, 2, 3); \hfill /* call function with pointer */
\rb
}

A ^{property pointer} is used in essentially the same way.

{\example
f: function(actor, obj)
\lb
    local propPtr := \&doTake;  \hfill /* get pointer to doTake property */
    obj.(propPtr)(actor);      \hfill /* call property through pointer */
\rb
}

For example, suppose you wish to implement a way of asking characters
in a game about various objects in the game.  One way you could do this
is by defining a general ``ask'' routine that takes the character and
the object as arguments.  Set things up so that each object defines
a property saying what each actor knows about that object.  Then,
each actor specifies via a ``property pointer'' which property to
evaluate in an object to find out what the actor knows about the
object.  If an object doesn't define this property, the actor doesn't
know anything about that object.

So, our general ``ask'' routine is very simple (or concise, anyway):

{\example
ask: function(actor, obj)
\lb
    local propPtr;
\vskip 12pt
    /* find out what property to evaluate in the object */
    propPtr := actor.askPropPtr;
\vskip 12pt
    /* see if it's defined in the object */
    if (defined(obj, propPtr))
    \lb
        /* it is defined - call the property indirectly */
        obj.(propPtr);
    \rb
    else
    \lb
        /* it's not defined - use default message */
        actor.dontKnow;
    \rb
\rb
}

Now, each actor simply has to define a property that each object uses
to specify what the actor knows about the object, and place the address
of this property the actor's {\tt askPropPtr} property.  The actor
also needs to define the default message in the {\tt dontKnow} property.
Here's an example:

{\example
\object{joe: Actor}
    sdesc = "joe"
    noun = 'joe'
    dontKnow = "Joe just scratches his head and shrugs."
    askJoe = "You probably don't want to get Joe started on his life story."
    askPropPtr = askJoe
\endobj
}

Finally, each object must define an appropriate {\tt askJoe} property
if Joe knows anything about that object.  Likewise, it will define
other properties for what other actors know about it.  This way,
all of the information about an object, including what the various
characters in the game know about it, can be kept with the object
itself.  In addition, the general ``ask'' routine is extremely
simple.  The overall concept behind the mechanism is somewhat
complicated, but the finished product is very simple and easy
to use and expand.


\minorsection{return}

A function can ^{return} a value to its caller by using a statement such as:

{\example
    return {\it [ expression ]};
}

With or without the {\it expression}, execution of
the function is terminated and
the caller resumes execution where it left off.  If the {\it expression} is
provided, the caller receives the expression as the function's value.

Here's an example of a function that computes the sum of the elements
of a list, and returns the sum as the value of the function.

{\example
    listsum: function(lst)
    \lb
        local i, sum, len := length(lst);
        for (i := 1, sum := 0 ; i <= len ; i++)
        \invislb
            sum += lst[i];
        \invisrb
        return(sum);
    \rb
}

\minorsection{if}

The general form of the conditional in TADS is:

{\example
    ^{if} ( {\it expression} ) {\it statement}
    {\it [} else {\it statement ]}
}

Here and elsewhere, a {\it statement} can be either a single statement or
a series of statements enclosed in ^{braces}.  The {\it expression} should
evaulate to either a number, in which case zero counts as false and
anything else counts as true, or to a truth value, {\tt true} or {\tt nil}.

Note that the optional {\tt ^{else}} clause is grouped with the most recent
{\tt if} statement when {\tt if} statements are nested. For example,

{\example
    if (self.islit)
    \invislb
        if (film.location = Me)
        \invislb
            "Oops! You've exposed the film!";
        \invisrb
    \invisrb
    else
    \invislb
        "It's dark in here.";
    \invisrb
}

The author of this code obviously intended the {\tt else} clause to go
with the first {\tt if}, but remember that an {\tt else} goes with the
{\it most recent} {\tt if}, so it actually is grouped with the second {\tt if}
statement.  This problem can be easily rectified by using braces to make the
grouping explicit:

{\example
    if (self.islit)
    \lb
        if (film.location = Me)
	\lb
	    "Oops! You've exposed the film!";
	\rb
    \rb
    else
    \lb
        "It's dark in here.";
    \rb
}

\minorsection{switch}

The {\tt ^{switch}} statement lets you set up the equivalent of a
large {\tt if}-{\tt else} tree, but is considerably easier to read
and is more efficient to execute.  A {\tt switch} statement allows
you to test a particular value against several alternatives, and
execute a group of statements accordingly.

The form of the {\tt switch} statement is:

{\example
    switch ( {\it expression} )
    \lb
        {\it [ case-list ]}
        {\it [ default-clause ]}
    \rb
}

The form of the {\it case-list} is:

{\example
    case {\it constant-expression} :
    \invislb
        {\it [ statements ]}
    \invisrb
\vskip 12pt
    {\it [ case-list ]}
}

The form of the {\it default-clause} is:

{\example
    default:
    \invislb
        {\it [ statements ]}
    \invisrb
}

In the diagrams, {\it statements} means that zero or more statements
can follow a {\tt case} or {\tt default}.  You do not need to
supply any {\tt case} labels at all, and the {\tt default} is also
optional.

The {\it expression} evaluates to a number, string, object, list, or
{\tt true} or {\tt nil}.  The value of the expression is then tested
against each {\tt ^{case}} value.  If the value matches one of the {\tt
case} values, the statements following the matching {\tt case} are
executed.  If the value does not match any {\tt case} value, and
a {\tt default} case is defined, the statements following the
{\tt default} are executed.  If the value does not match any {\tt case}
value, and there is no {\tt default} case, the entire {\tt switch}
statement is skipped, and execution resumes following the closing
brace of the {\tt switch}.

Note that execution is {\it not} interrupted when another {\tt case}
is enountered.  Instead, it just continues into the statements
following the {\tt case} label.  If you wish to stop executing
statements in the {\tt switch} at the end of the statements for
a single {\tt case}, you must use the {\tt break} statement.

The {\tt ^{break}} statement has a special meaning within a {\tt switch}
statement:  it indicates that execution should break out of the
{\tt switch} statement and resume following the closing brace
of the {\tt switch}.

Here's an example of a {\tt switch} statement.

{\example
f: function(x)
\lb
    switch(x)
    \lb
    \hskip-1em case 1:
        "x is one";
        break;
    \hskip-1em case 2:
    \hskip-1em case 3:
        "x is either 2 or 3";
        break;
    \hskip-1em case 4:
        "x is 4";
    \hskip-1em case 5:
        "x is either 4 or 5";
    \hskip-1em case 6:
        "x is 4, 5, or 6";
        break;
    \hskip-1em case 7:
        "x is 7";
        break;
    \hskip-1em default:
        "x is not in 1 through 7";
    \rb
\rb
}


\minorsection{while}

The {\tt ^{while}}
statement defines a loop:  a set of statements that is executed
repeatedly as long as a certain condition is true.

{\example
    while ( {\it expression} ) {\it statement}
}

As with the {\tt if} statement, the {\it statement}
may be a single statement or a
set of statements enclosed in braces.  The {\it expression}
should be a number
(in which case 0 is false and anything else is true), or a truth
value ({\tt true} or {\tt nil}).

The {\it expression} is evaluated {\it before} the first time through
the loop; if the {\it expression} is false at that time, the statement or
statements in the loop are skipped.  Otherwise, the statement or statements
are executed once, and the {\it expression} is evaluated again; if the
{\it expression} is still true, the loop executes one more time and the
cycle is repeated.  Once the {\it expression} is false, execution resumes
at the next statement after the loop.

\minorsection{do-while}

The {\tt ^{do-while}} statement defines a slightly different type
of loop than the {\tt while} statement.  This type of loop also executes
until a controlling expression becomes false (0 or {\tt nil}), but
evaluates the controlling expression {\it after} each iteration of
the loop.  This ensures that the loop is executed at least once, since
the expression isn't tested for the first time until after the first
iteration of the loop.

The general form of this statement is:

{\example
    do {\it statement} while ( {\it expression} );
}

The {\it statement} may be a single statement or a set of statements
enclosed in braces.  The expression should be a number (in which case
0 is false and anything else is true), or a truth value ({\tt true}
or {\tt nil}).

\minorsection{for}

The {\tt ^{for}} statement defines a very powerful and general
type of loop.  You can always use {\tt while} to construct any loop
that you can construct with {\tt for}, but the {\tt for} statement
is often a much more compact and readable notation for the same
effect.

The general form of this statement is:

{\example
    for ( {\it init-expr} ; {\it cond-expr} ; {\it reinit-expr} ) %
 {\it statement}
}

As with other looping constructs, the {\it statement} can be either
a single statement, or a block of statements enclosed in braces.

The first expression, {\it init-expr}, is the ``initialization
expression.''  This expression is evaluated once, before the
first iteration of the loop.  It is used to initialize the
variables involved in the loop.

The second expression, {\it cond-expr}, is the condition of the
loop.  It serves the same purpose as the controlling expression
of a {\tt while} statement.  Before each iteration of the loop,
the {\it cond-expr} is evaluated.  If the value is true (a non-zero
number, or {\tt true}), the body of the loop is executed; otherwise,
the loop is terminated, and execution resumes at the statement
following the loop body.  Note that, like the {\tt while} statement's
controlling expression, the {\it cond-expr} of a {\tt for} statement
is evaluated prior to the first time through the loop (but after
the {\it init-expr} has been evaluated), so a {\tt for} loop will
execute zero times if the {\it cond-expr} is false prior to the
first iteration.

The third expression, {\it reinit-expr}, is the ``re-initialization
expression.'' This expression is evaluated {\it after} each iteration
of the loop.  Its value is ignored; the only purpose of this expression
is to change the loop variables as necessary for the next iteration of
the loop.  Usually, the re-initialization expression will increment a
counter or perform some similar function.

Any or all of the three expressions may be omitted.  Omitting the
expression condition is equivalent to using {\tt true} as the
expression condition; hence, a loop that starts ``{\tt for ( ;; )}''
will iterate forever (or until a {\tt break} statement is executed
within the loop).  A {\tt for} statement that omits the initialization
and re-initialization expressions is the same as a {\tt while} loop.

Here's an example of using a {\tt for} statement.  This function
implements a simple loop that computes the sum of the elements of
a list.

{\example
sumlist: function(lst)
\lb
    local len := length(lst), sum, i;
    for (sum := 0, i := 1 ; i <= len ; i++)
    \invislb
        sum += lst[i];
    \invisrb
\rb
}

Note that an equivalent loop could be written with an empty loop
body, by performing the summation in the re-initialization expression.
We could also move the initialization of {\tt len} within the
initialization expression of the loop.

{\example
sumlist: function(lst)
\lb
    local len, sum, i;
    for (len := length(lst), sum := 0, i := 1 ; i <= len ;
    \hskip 2em sum += lst[i], i++);
\rb
}


\minorsection{break}

A program can get out of a loop early using the {\tt ^{break}} statement:

{\example
    break;
}

This is useful for terminating a loop at a midpoint.  Execution resumes at the
statement immediately following the innermost loop in which the break appears.

The {\tt break} statement also is used to exit a {\tt ^{switch}} statement.
In a {\tt switch} statement, a {\tt break} causes execution to resume
at the statement following the closing brace of the {\tt switch}
statement.

\minorsection{continue}


The {\tt ^{continue}} statement does roughly the opposite of the {\tt break}
statement;  it
resumes execution back at the start of the innermost loop in which it appears.
The {\tt continue} statement may be used in {\tt for}, {\tt while},
and {\tt do-while} loops.

In a {\tt ^{for}} loop, {\tt continue} causes execution to resume
at the re-initiailzation step.  That is, the third expression (if
present) in the {\tt for} statement is evaluated, then the second
expression (if present) is evaluated; if the second expression's
value is non-nil or the second expression isn't present, execution
resumes at the first statement within the statement block following
the {\tt for}, otherwise at the next statement following the block.

\minorsection{goto}

The {\tt ^{goto}} statement is used to transfer control unconditionally
to another point within the same function or method.  The target of
a {\tt goto} is a ^{label}; a label is defined by placing its name,
followed by a colon ({\tt :}), preceding a statement.

Note that labels have function- or method-scope; that is, they are
visible within the entire function or method in which they are
defined.  This is different from local variables, which are visible
only within the {\it block} (the group of statements enclosed in
braces) in which they are defined.  Labels are not visible outside
the function or method in which they are defined.

An example of using {\tt goto}:

{\example
f: function
\lb
    while (true)
    \lb
        for (x := 1 ; x < 5 ; x++)
        \lb
            /* do some stuff */
            if (myfunc(3) < 0)   \hfill /* did an error result? */
            \invislb
                goto exitfunc;   \hfill /* error - quit now */
            \invisrb
            /* do some more stuff */
        \rb
    \rb
\vskip 12pt
    /* come here if something goes wrong */
\hskip-1em exitfunc: ;
\rb
}

This use of {\tt goto} avoids the need for testing a flag in the
outer ({\tt while}) loop, which makes the code a little simpler
and easier to understand.

The {\tt goto} statement is widely considered among civilized
computer scientists to be an evil and malevolent feature of
ancient and unusable languages, and the esteem of
TADS within serious computer language design circles has undoubtedly
been fatally injured by the inclusion of this construct.  So, you
may wish to use this statement sparingly, if at all, especially
if you're hoping to impress a civilized computer scientist with
your coding efforts.  However, many software engineers look upon
{\tt goto} as a highly useful statement when in the hands of a
seasoned professional, and scoff at the blanket indictment by
the more-elegant-than-thou academic establishment, most of whom
probably haven't written a line of code since {\it their} TA's
were chastising them for using {\tt goto} in their Pascal programs,
excepting perhaps some algorithms written in pseudo-code that
always end in ``the rest is left as an exercise for the reader''
anyway.  The author of TADS doesn't wish to take sides
in this heated controversy, but hopes that both camps will
be pleased, by gaining either the utility of using {\tt goto} with
wild abandon or the sense of virtue of knowing they could have
used it but overcame the unclean temptation.  With TADS, the choice
is yours.


\minorsection{pass}


A method can decide to inherit the behavior of its parent class by using
the {\tt ^{pass}} statement:

{\example
    pass {\it method-name};
}

The {\it method-name} must be the same as the name of the method that
the {\tt pass} statement occurs in.  When a {\tt pass} statement is
executed, the ^{method} that would have been inherited if the object had
not overridden it is called with the same ^{arguments}, if any, as the
method called in the first place.  The {\tt self} object is unchanged;
that is, the superclass method is run, but {\tt self} is the object that
was originally sent the message being passed.

\minorsection{exit and abort}


During processing of a ^{player's command}, the game can terminate the normal
sequence of events and return to the get another command from the player
in two different ways.  The {\tt ^{abort}} statement stops all processing,
and gets the next command; it is normally used by ``system" functions, such
as saving the game, that should not count as a turn, and therefore shouldn't
run any daemons or fuses.  The {\tt ^{exit}} statement, on the other hand,
skips everything up to the fuses and daemons; {\tt exit} is used when an
actor wishes to stop further processing, and other similar cases.

Note
that messages to objects scheduled with the {\tt ^{notify()}} function are
treated the same as other daemons and fuses, so these are also skipped by
the {\tt abort} statement.

\minorsection{askdo and askio}


These statements interrupt processing of a turn like {\tt ^{abort}}, skipping
fuses and daemons, but allow the user to enter more information.  The
{\tt ^{askdo}} command asks the user to enter a ^{direct object}; the system
displays a message asking the user for an object.  The user can either
enter an object in response to the request, or can simply type a new command.
For example, if the verb is ``take," executing an {\tt askdo} command will
cause the system to display ``What do you want to take?" and wait for an
object or a new command.  The {\tt ^{askio}} command is similar, but it takes
a ^{preposition} as a parameter; this preposition is added to the command, and
the system prompts the player for an ^{indirect object}.  For example, if the
verb is ``unlock," and the following command is executed:

{\example
    askio(withPrep);
}

then the system displays ``What do you want to unlock it with?" and prompts
the player for an object or a new command.  The {\tt askio} command can only
be used when a direct object is already present.

In either case, if the player responds to the request with an object, the
command is tried again from the start. If the player types a new command,
the command that resulted in the {\tt askdo} or {\tt askio} is discarded.
Note that control never comes back
to the statement after the {\tt askdo} or {\tt askio} command, regardless
of user input; in either case, command processing starts from the top.

Note that, in some cases, the system won't actually ask the player
for a new object.  Instead, the system will attempt to find a default
object, using exactly the same mechanisms that it uses to find default
objects normally (see the section on the parser's default object
mechanisms in chapter four).


\minorsection{self}


When code associated with a property is being executed, a special object is
defined, called {\tt ^{self}}.
This special object refers to the object whose property is
being evaulated.  This may not sound too useful, but consider the case of
an object whose ^{superclass}
defines a ^{property} which refers to other properties
of the ^{object}:

{\example
    \object{class book: object}
        description =
	\lb
	     "The book is << self.color >>.";
        \rb
    \endobj
    
    \object{redbook: book}
        color = "red"
    \endobj
    
    \object{bluebook: book}
        color = "blue"
    \endobj
}

In this example, the general object, {\tt book},
knows how to describe a book given
its color.  The books that are defined, the {\tt redbook} and {\tt bluebook}
objects, take
advantage of this by simply defining their color, and letting the description
property of their superclass be used to describe them.  So, when you attempt
to evaluate {\tt redbook.description}, you get

{\example
    The book is red.
}

\minorsection{inherited}

A special pseudo-object called {\tt ^{inherited}} allows you to call
a method in the current {\tt self} object's superclass.  This pseudo-object
is similar to the {\tt pass} statement, but much more useful in several
ways.  First, with {\tt inherited}, you can simply {\it call} the
superclass method, and regain control when it returns; with {\tt pass},
the current method never regains control.  Second, you can use {\tt
inherited} in an expression, so any value returned by the superclass
method can be determined and used by the current method.  Third, you
can pass arguments to the property invoked with the {\tt inherited}
pseudo-object.

You can use {\tt inherited} in an expression anywhere that you
can use {\tt self}.

Here is an example of using {\tt inherited}.

{\example
\object{myclass: object}
    sdesc = "myclass"
    prop1(a, b) =
    \lb
       "This is myclass's prop1.  self = << self.sdesc >>,
        a = << a >>, and b = << b >>.\char`\\n";
        return(123);
    \rb
\endobj

\object{myobj: myclass}
    sdesc = "myobj"
    prop1(d, e, f) =
    \lb
        local x;
        "This is myobj's prop1.  self = << self.sdesc >>,
        d = << d >>, e = << e >>, and f = << f >>.\char`\\n";
        x := inherited.prop1(d, f) * 2;
        "Back in myobj's prop1.  x = << x >>\char`\\n";
    \rb
\endobj
}

When you call {\tt myobj.prop1(1, 2, 3)}, the following will be displayed:

{\example
  This is myobj's prop1. self = myobj, d = 1, e = 2, and f = 3.
  This is myclass's prop1. self = myobj, a = 1, and b = 3.
  Back in myobj's prop1. x = 246.
}

Note one feature of {\tt inherited} that is the same as {\tt pass}:  the
{\tt self} object that is in effect while the superclass method is
being executed is the {\it same} as the {\tt self} object in the
calling (subclass) method.  This makes {\tt inherited} very different
from calling the superclass method directly (i.e., by using the
superclass object's name in place of {\tt inherited}).

\minorsection{argcount}

The pseudo-variable {\tt ^{argcount}} returns the number of arguments
to the current function.  This can be used for functions that take
a variable number of arguments to learn the number of arguments that
need to be processed.  Note that {\tt argcount} isn't really a variable,
so you can't assign a value to it, but otherwise you can use it as
though it were an ordinary variable.

\majorsection{Built-in Functions}


The system has a set of ^{built-in functions} to facilitate writing programs.
The functions are described in this section.  They operate just like ordinary
functions, with the exception that built-in functions which don't take
arguments don't require parentheses; this simplifies coding of some special
cases.

\minorsection{askfile}

Call:  {\tt ^{askfile}({\it prompt})}

This function asks the user to enter a filename, in a system-dependent manner.
The system's standard file dialog, if the computer has one, will be used;
otherwise, the user may simply be prompted to type a filename.  The {\it
prompt} (a single-quoted string value) may or may not be used,
depending on system conventions; for systems
without any defined standard file dialog, it will be displayed to prompt the
user for a filename.

This function is primarily useful for operations such as saving and restoring
games which require that the user enters a system filename.

\minorsection{caps}

Call:  {\tt ^{caps}()}

Forces the next non-space character to be displayed to be capitalized.  This
is useful for formatting output when it is not known in advance whether an
item will be displayed at the start of a sentence or not.

Note that displaying the sequence ``{\tt \char`\\ \char`\^}" has the same
effect as calling {\tt caps()}.

Do not confuse this function with the {\tt upper({\it string})} built-in
function, which converts all of the letters in a string to upper-case.
The {\tt caps()}
function takes no arguments, and affects only the next character output.

\minorsection{car}

Call:  {\tt ^{car}({\it list})}

Returns the first element of a ^{list}, or {\tt ^{nil}} if the list is empty.

Note that the same value can be retrieved with the expession
{\it list}{\tt [1]}, which uses the ^{list indexing} operator to retrieve
the first element of {\it list}.  The primary difference between using
{\tt car()} and the ^{list} indexing operator is the style of your program;
using {\tt car()} and {\tt ^{cdr()}} to decompose a list, you can iterate
or recurse until you run out of list to process, at which time {\tt car()}
will return {\tt nil}.  With the list indexing operator, however, you need
to know in advance how many elements are in the list; this information can
be learned with the {\tt ^{length()}} built-in function.  The choice of one
of these methods over another is a matter of personal preference.

\minorsection{cdr}

Call:  {\tt ^{cdr}({\it list})}

Returns the end of a list; that is, the list of everything after the list's
{\tt car()}.  With {\tt ^{car}()} and {\tt cdr()}
you can decompose a ^{list} into its individual elements.

\minorsection{cvtnum}

Call:  {\tt ^{cvtnum}({\it string})}

This function converts a string that contains the text version of a number
into a numeric value.  For example, {\tt cvtnum('1234')} returns the
number {\tt 1234}.  Note that the special strings {\tt 'true'} and {\tt 'nil'}
are also accepted by the function, and are converted to the logical values
{\tt ^{true}} and {\tt ^{nil}}, respectively.

\minorsection{cvtstr}

Call:  {\tt ^{cvtstr}({\it value})}

This function converts a numeric or logical value into its string
representation.  For example, {\tt cvtstr(1234)} returns the string
{\tt '1234'}, {\tt cvtstr(true)} returns the string {\tt 'true'}, and
{\tt cvtstr(nil)} returns the string {\tt 'nil'}.

\minorsection{datatype}

Call:  {\tt ^{datatype}({\it value})}

This function returns the type of a value.  It is useful primarily
with functions that take a variable number of arguments, but could
also be useful for inspecting lists whose contents vary.
^^{varargs functions}
^^{variable argument lists}

This function returns a numeric value based on the datatype.

\medskip
{\advance\leftskip2in
\def\datitem#1{\medskip\indent\llap{\hbox to 1in{{#1}\hfill}}}
\parskip=1pt

\datitem{1}Number
\datitem{2}Object
\datitem{3}String
\datitem{5}{\tt nil}
\datitem{7}List
\datitem{8}{\tt true}
\datitem{10}Function Pointer
\datitem{13}Property Pointer

\medskip}

\minorsection{defined}

Call:  {\tt ^{defined}({\it object, propPointer})}

This function allows you to determine if a property is defined or
inherited by an object, or if the object doesn't have any value for
the property.  This function returns {\tt true} if the the object
has a definition for the property (either explicitly in the object,
or inherited from a superclass), or {\tt nil} if the object doesn't
have any definition for the property.

Note that the {\it propPointer} argument must be a property {\it pointer}.
You can obtain a property pointer using the {\tt ^{\&}} operator with
a property name.  For example, to determine if the player's current
location has an {\tt ldesc} property defined, you would do this:

{\example
    x := defined(Me.location, \&ldesc);
}

In this example, {\tt x} is {\tt true} if the current location has
an {\tt ldesc} property defined, and {\tt nil} otherwise.

\minorsection{find}

Call:  {\tt ^{find}({\it value}, {\it target})}

If {\it value} is a ^{list}; 
the function returns the offset (starting at 1 for
the first element) in the list of the {\it target} item within the {\it value}
list.  If the {\it target} is not found, {\tt nil} is returned.  For example,
{\tt find([4 5 6], 5)} returns {\tt 2}.

If {\it value} is a ^{string},
in which case {\it target} must also be a string,
the function will return the offset within the string {\it value} of the
substring {\it target}, or {\tt nil} if the substring is not found.  The
offset of the first character in the {\it target} string is 1.  For example,
{\tt find('abcdefghij', 'cde')} returns {\tt 3}.

\minorsection{firstobj}

Call:  {\tt ^{firstobj}()}

Alternative Call: {\tt firstobj({\it class})}

This function is used in conjunction with {\tt ^{nextobj}({\it object})} to
loop over all non-class objects in the game.  The {\tt firstobj()} function
returns the first non-class object, and {\tt nextobj({\it object})} is
used to retrieve subsequent objects in a loop.  The order of the objects
returned by these functions is arbitrary, but calling {\tt firstobj()}
and then sequentially calling {\tt nextobj({\it object})} until {\tt nil}
is returned will guarantee that each non-class object is retrieved exactly
once.

These functions are useful primarily during initialization to construct
lists of all objects satisfying certain search criteria; these lists can
be used later in the game to expedite searches for objects with such
criteria.  For example, code that determines if a room is dark will have
to always check to see if a light-providing object, such as a lamp or a
burning candle, is present.  It will be faster during game play to check
only those objects known to be light-providing than to check all objects
in the game; to accomplish this, we could set a property called {\tt islamp}
to {\tt true} in every potential light-providing object, then construct
a list of all such objects during initialization with the example code
below.

{\example
    getlamps: function
    \lb
        local obj, l;
	
	l := [];
	obj := firstobj();
	while(obj <> nil)
	\lb
	    if (obj.islamp) l := l + obj;
	    obj := nextobj(obj);
	\rb
	global.lamplist := l;
    \rb
}

After initialization, then, it is only necessary to check for the presence
of one of the objects in the list {\tt global.lamplist}, rather than checking
all objects in the game, to determine if a room is lit or not.

Note that {\tt firstobj()} will return {\tt nil} if the game has no non-class
objects.  Likewise, {\tt nextobj({\it object})} returns {\tt nil} when the
last non-class object has been retrieved.

The alternative form of this function, with a single argument giving
a class object, allows you to restrict the objects returned by
{\tt firstobj()} and {\tt nextobj()} to those that are subclasses
of a particular class.  This can save a great deal of time by ignoring
objects that are not important to your search.  For the example above,
you could make the loop execute much more quickly by rewriting it
as follows.

{\example
    getlamps: function
    \lb
        local obj, l;
	
	l := [];
	obj := firstobj(lampitem);
	while(obj <> nil)
	\lb
	    l := l + obj;
	    obj := nextobj(obj, lampitem);
	\rb
	global.lamplist := l;
    \rb
}

Note that the test for {\tt obj.islamp} is no longer necessary,
because only objects that are subclasses of the class {\tt lampitem}
will be used in the loop.  By iterating over a much smaller set of
objects, the loop will execute substantially faster.

\minorsection{getarg}

Call:  {\tt ^{getarg}({\it argnumber})}

This function returns the argument given by {\it argnumber}, which is
a number from 1 to the number of arguments to the function (which can
be learned with the pseudo-variable {\tt ^{argcount}}).  {\tt getarg(1)}
returns the first argument to the current function,
{\tt getarg(2)} returns the second argument,
and so forth, up to {\tt getarg(argcount)}.  This function can be used
to retrieve the arguments to functions taking a variable number of
arguments.

\minorsection{incturn}

Call:  {\tt ^{incturn}()}


Increments the turn counter.  Normally, a ^{daemon} is present to call this
function once per player command.  The turn counter is used to time the
execution of ^{fuses}, so the user must call {\tt incturn()} once per turn.

This function is not called automatically by the system, since the turn
counter should not be incremented after certain events.  For example, most
system commands, such as saving a game, should not count as a turn.  This
function is provided so that the game program can decide when to increment
the counter.

\minorsection{input}

Call:  {\tt ^{input}()}


This function stops and waits for the user to enter a line of text
(terminated by the return key and edited as normal for command lines),
and returns a string containing the text the user enters.  This function
does not display any prompt, so it is up to the game program to prompt
the user before calling this function.

As a stylistic point, this function should normally be avoided except for
special system functions, since the game will present a more consistent
interface if the command line is used for most player input. One possible
use is given by the example below.  (Note that this code is somewhat
simplified; in an actual game, you would also want to call {\tt setscore()}
at the appropriate points, and provide other useful feedback.)

{\example
    die: function
    \lb
        "*** You have died ***
	\char`\\bDo you wish to RESTART, RESTORE, or QUIT? >";
	while (true)
	\lb
            local response;
	    
	    response := upper(input());
	    if (response = 'RESTART') restart();
	    else if (response = 'RESTORE')
	    \lb
	        response := askfile();
		if (restore(response)) "Failed. ";
		else abort;
	    \rb
	    else if (response = 'QUIT')
	    \lb
	        quit();
		abort;
	    \rb
	    else "Please enter RESTORE, RESTART, or QUIT: >";
	\rb
    \rb
}

\minorsection{isclass}

Call:  {\tt ^{isclass}({\it object, class})}

This function determines if an object is a subclass of a given class.
It returns {\tt true} if {\it object} is a subclass of {\it class},
{\tt nil} otherwise.  Note that the function scans the entire class
tree, so {\it class} need not be in the immediate superclass list for
{\it object}, but can be a superclass of a superclass of {\it object},
or a superclass of a superclass of a superclass, and so on.

This function should be used to determine if an object is a member
of a class, rather than using a special property value that the
object inherits from the class.  Using {\tt isclass} is more efficient
than using a special inherited property value, because the property
value doesn't need to be stored, and because it is much faster to
scan the inheritance tree than to check each object in the tree for
the property value.

\minorsection{length}

Call: {\tt ^{length}({\it item})}


If the {\it item} is a string, {\tt length()}
returns the number of characters in the
string.  If {\it item} is a list, {\tt length()}
returns the number of elements in the list.

\minorsection{logging}

Call:  {\tt ^{logging}({\it value})}


If the {\it value} is a ^{string},
it specifies the name of an operating system file
which will be created (or truncated to zero length if it already exists) and
to which subsequent information displayed on the screen is duplicated.  That
is, a complete log of the play will be copied to the file for later inspection.

If the {\it value} is {\tt nil},
it indicates that a log file, if in effect, should be
closed and logging halted.

^{Logging} is automatically terminated when the player quits the game, but
other operations (including saving, restoring, and restarting a game) do
not affect logging.

This function has no return value.

\minorsection{lower}

Call:  {\tt ^{lower}({\it string})}

This function returns a copy of {\it string} with all of the upper-case
letters converted to lower-case.  See also the {\tt upper({\it string})}
function.

\minorsection{nextobj}

Call:  {\tt ^{nextobj}({\it object})}

Alternative Call:  {\tt nextobj({\it object, class})}

This function is used to retrieve the next object in a search started
with {\tt ^{firstobj}()}.  The {\it object} is the value returned by the call
to {\tt firstobj()} or by the previous {\tt nextobj({\it object})} call.
The next non-class object after {\it object} is returned, and {\tt nil} is
returned if {\it object} was the last non-class object.

The alternative form, with a second argument giving a class object,
returns the next object that is a subclass of the given class.  This
can be used to restrict the search to a particular class of objects.

For an example of the use of this function, see the description of the
{\tt firstobj()} built-in function.

\minorsection{notify}

Call: {\tt ^{notify}({\it object}, \&{\it message}, {\it turns})}

This function sets up to send the {\it message} to the {\it object} after
the given number of {\it turns} has elapsed, or, if {\it turns} is zero,
after each turn.  Note the {\tt \&} before the {\it message} parameter; this
is required to indicate that the {\it message} is to be stored rather than
being sent immediately.

The {\it message} is simply the name of a method defined by the {\it
object}.  The method receives no parameters when it is called.

There is a limit of 100 simultaneously pending notifications.

With a non-zero number of {\it turns}, the {\tt notify()} function is
similar to the {\tt setfuse()} function, in that it waits a given number of
turns and then sends the specified {\it message} to the given {\it object}.
With {\it turns} set to zero, {\tt notify} is similar to {\tt setdaemon()},
in that the {\it message} is sent to the {\it object} after each turn.
Note that
the {\tt notify()} function is generally the better function to use, since
most ^{fuses} and ^{daemons}
are directed at objects, and it is better to keep all
code that affects the object in the object's definition, rather than move
some into a separate function.

See also the {\tt unnotify()} function, which cancels the effect of the
{\tt notify()} function.

An example of the {\tt notify()} function is shown below.  In the example,
we define two objects:  a bomb, and a button on the bomb.  When the button
is pushed, it calls {\tt notify()} to specify that the {\tt explode} method
in the object {\tt bomb} is to be called in three turns.

{\example
    \object{bomb: item}
        location = bombroom
	sdesc = "bomb"
	noun = 'bomb'
	ldesc =
	\lb
	    "The bomb seems to have a small button marked
	    \char`\\"detonator\char`\\" on it. ";
	    if (self.isActive) "It's ticking loudly. ";
	\rb
	explode =
	\lb
	    "The bomb explodes! ";
	    self.moveInto(nil);
	\rb
    \endobj

    \object{bombButton: buttonItem}
        location = bomb
	sdesc = "detonator button"
	adjective = 'detonator'
        doPush(actor) =
	\lb
	    "The bomb starts ticking. ";
	    notify(bomb, \&explode, 3); \hfill// Bomb explodes in three turns
	    bomb.isActive := true;
	\rb
    \endobj
}

\minorsection{proptype}

Call:  {\tt ^{proptype}({\it object, propPointer})}

This function determines the datatype of a property of an object,
without actually evaluating the property.  This can be useful if
you want to find out what kind of value the property has, without
activating any side effects of evaluating the property (for example,
displaying a double-quoted string contained by the property).

The return value is a number, and the possible values are a superset
of those returned by the {\tt ^{datatype}()} built-in function.

\medskip
{\advance\leftskip2in
\def\datitem#1{\medskip\indent\llap{\hbox to 1in{{#1}\hfill}}}
\parskip=1pt

\datitem{1}Number
\datitem{2}Object
\datitem{3}String
\datitem{5}{\tt nil}
\datitem{6}Code (executable statements enclosed in braces)
\datitem{7}List
\datitem{8}{\tt true}
\datitem{9}Double-quoted string
\datitem{10}Function Pointer
\datitem{13}Property Pointer

\medskip}

Note that the {\it propPointer} argument must be a property pointer.
You can get a property pointer by using the {\tt ^{\&}} operator on
a property name.  For example, to determine the type of the {\tt north}
property of the player's current location, you would do this:

{\example
    x := proptype(Me.location, \&north);
}

Note that using {\tt proptype()} is very different from using the
{\tt ^{datatype}()} built-in function on the value of the property,
because {\tt proptype()} does {\it not} evaluate the property in
order to determine its type.  This has several implications.  First,
and most importantly, it allows you to avoid side effects of evaluating
the property (such as displaying a double-quoted string value) if you
don't desire the side effects.  Second, it means that you will find out
if a property contains code, but you will {\it not} learn what type of
value (if any) the code will return.

\minorsection{quit}

Call:  {\tt ^{quit}()}

Terminates the game.  Actually, this function flags that the game is to be
ended the next time a command will be parsed, so normal return codes should
be passed back when using {\tt quit()}.  Hence, after calling {\tt quit()},
you should always immediately execute an {\tt abort} statement.  See the
example given in the description of the {\tt input()} built-in function
for an illustration of the use of {\tt quit()}.

\minorsection{rand}

Call:  {\tt ^{rand}({\it upper-limit})}

This function returns a random number from 1 to the {\it upper-limit} given.
(The {\it upper-limit} must be a positive number.)  See also the discussion
of {\tt randomize()}, below.

\minorsection{randomize}

Call:  {\tt ^{randomize}()}

This function ``seeds" the random number generator with a new value.  The
value is implementation-defined, and comes from such a source as the system
clock.  Until {\tt randomize()} is called, the random number generator will
always produce a fixed sequence of random numbers; once randomized, however,
the sequence is unpredictable.  For testing purposes, you can leave the
call to {\tt randomize()} out of your program, because the game will always
run repeatably.  Once the game is working, you can simply put a call to
{\tt randomize()} in your {\tt init()} function in order to make the game
unpredictable for your players.

\minorsection{remdaemon}

Call:  {\tt ^{remdaemon}({\it function}, {\it value})}

Removes a ^{daemon} set previously with {\tt ^{setdaemon}()}.
The daemon will no longer be called.  Note that if a given function has
been set as a daemon multiple times, a call to {\tt remdaemon()} only removes
the first such daemon; hence, you must call {\tt remdaemon()} as many times
as you called {\tt setdaemon()} on a particular function if you wish to
cancel all calls to it.  Note also that the {\it value} given must match
the {\it value} used in the original call to {\tt setdaemon()}; this allows
you to set a daemon several times, with different contexts (the context
being given by the {\it value}), and selectively remove the daemons later.

\minorsection{remfuse}

Call:  {\tt ^{remfuse}({\it function}, {\it value})}

See also the {\tt ^{setfuse}()} built-in function.
This function removes a ^{fuse} previously set, or does nothing if the named
function has not been set as a fuse.  The fuse will not be executed if removed
prior to burning down.  Note that if a function has been set as a fuse
multiple times, {\tt remfuse()} will remove only the first such fuse set;
hence, you must call {\tt remfuse()} on a function as many times as you
called {\tt setfuse()} on the function if you wish to cancel all calls to it.
Note also that the {\it value} given must match the {\it value} used in the
original call to {\tt setdaemon()}; this allows you to set a fuse several
times, with different contexts (the context being given by the {\it value}),
and selectively remove the fuses later.

\minorsection{restart}

Call:  {\tt ^{restart}()}

This function starts the game over again from the beginning.  It does not
return.

\minorsection{restore}

Call:  {\tt ^{restore}({\it filename})}

The {\it filename}
is a string specifying an operating system file which was created
with the {\tt ^{save}()} function.
The state of the previously saved game is restored,
so that the players can continue where they left off.

If successful, {\tt ^{nil}} is returned;
otherwise, an error occurred restoring the game from the file.
Note that the game to be restored must have been saved by the identical
version of the TADS software {\it and} of the game itself. The system
will refuse to restore a game saved by a different version of the TADS
software, or by a different version of your game program (as determined
by a timestamp stored in the game by the compiler).

\minorsection{save}

Call:  {\tt ^{save}({\it filename})}

The {\it filename} is a string specifying an operating system file to be used
to save
the current status of the game.  Everything about the game is saved in the
file, so that the exact point in the game can be later restored with the
{\tt ^{restore}()} function.

If successful, {\tt nil} is returned;
otherwise, an error occurred saving the file.

\minorsection{say}

Call:  {\tt ^{say}({\it value})}

The {\it value} can be either a number or a string.
If it's a number, its decimal
value is printed.  A string is displayed as it is.

There is no return value.

\minorsection{setdaemon}

Call:  {\tt ^{setdaemon}({\it function}, {\it value})}

Sets a daemon.  Each turn, all outstanding daemons are called once, after
all player command processing is completed. The {\it value} given is passed
to the {\it function} as its sole parameter each time the function is called.

{\it Note:} the function must be known when the compiler reads this
statement, which means the function must have been defined or at least called
prior to the {\tt setdaemon()} call in the source file.  You can
^{forward-declare} a function by using a statement like this:

{\example
    test: function;
\medskip}

Note that the actual definition of the function {\tt test} will appear
later in the file; the statement above only declares it as a function so
it can be used in the {\tt setdaemon()} or similar call.

At most 100 daemons can be running simultaneously; a run-time error will
result if a call to {\tt setdaemon()} is made when 100 daemons are
already running.  There is no return value.

See also the {\tt notify()} function.

\minorsection{setfuse}

Call:  {\tt ^{setfuse}({\it function}, {\it time}, {\it value})}

Sets a ^{fuse} of the specified length.  The {\it function}
is the identifier naming
a function.  The {\it time} is a positive number specifying the number of turns
before the fuse burns down.  After the specified number of turns,
{\it function} is called with {\it value} as its sole parameter.

{\it Note:}
the function must be known as a function when the compiler reads this
statement, which means the function must have been defined or at least called
prior to the {\tt setfuse()} call in the source file.  See the note in the
description of {\tt setdaemon()}, above, for more information.

There is limit of 100 simultaneously pending fuses; a run-time error
results if {\tt setfuse()} is called when 100 fuses are already pending.
There is no return value from {\tt setfuse()}.

Note that fuses differ from ^{daemons} in that a fuse is only called once,
at a time determined when the fuse is set; once called, it is automatically
removed from the list of pending fuses. Daemons, on the other hand, are
called once per turn until explicitly removed.

\minorsection{setit}

Call:  {\tt ^{setit}({\it object})}



Sets the antecedant of ``^{it}," 
as used in a player's command, to the specified
object.  This is useful if a complaint refers to an object which will draw
the player's attention; consider the following dialogue:

{\example
    >go north
    The metal door is closed.
    >open it
    There is a padlock preventing you from opening the door.
    >unlock it
    What do you want to unlock the padlock with?
    >the key
    The padlock swings open.
\medskip}

In this example, {\tt setit()} has been used each time a complaint refers
to an
object which the user might wish to manipulate due to the complaint.

There is no return value.

\minorsection{setscore}

Call:  {\tt ^{setscore}({\it score}, {\it turns})}

Alternative Call:  {\tt setscore({\it stringval})}

This function is used to inform the system of the current score and turn
count.  On versions of TADS that have a ^{status line}, this function updates
the values on the status line.  On versions of TADS without a status line,
this call is ignored.

Your game should call this function whenever the score or turncounter
change, so that the status line is always kept up to date.  Note that
this means that it should be called after using {\tt restore()} to load
an old game, and before calling {\tt restart()} to start over from the
beginning, in addition to being called whenever the player earns points
or completes a turn.  Generally, if you use the function {\tt incscore()}
defined in {\tt adv.t} to add points to the score, and you use
a standard turn counter function (such as the {\tt turncount()} function
defined in {\tt adv.t}), you will not have to worry about calling
{\tt setscore()} too often.

The alternative form of the {\tt setscore()} call allows you to display
any text string in the score/turn counter area of the status line.  In
older versions of TADS, only the first form could be used, and the status
line display was fixed with the score/turn counter format.  In new
versions, however, you can place whatever string you want on the right
portion of the status line, simply by passing the string you wish to
display to the {\tt setscore()} function.  You could, for example,
display the time of day (within your game), or you could display the
player's rank, experience, or other statistics rather than the score.
The text string used in {\tt setscore()} is displayed right-justified
on the status line.

Note that several routines in {\tt adv.t} (about four in all) call the 
numeric form of
{\tt setscore()}.  If you use the string version, you should change
the {\tt setscore()} calls in {\tt adv.t} to call a routine that
you provide that displays the status line in the format you prefer.

\minorsection{setversion}

Call:  {\tt ^{setversion}({\it version})}

{\it Note:}  This function is no longer needed, although TADS continues
to support it for compatibility with existing games written with older
versions of TADS.  

In older version of TADS, this function was used to identify the version
of your game that created a saved game file.  It was necessary to use
{\tt setversion} so that a saved position file created by one version of
your game couldn't accidentally be used with another version of your
game, because the information in a saved position file is only usable
by the same version of a game that created it.
The compiler now automatically generates a unique
version identifier whenever your game is compiled, eliminating the need
for you to do this manually.  You no longer need to call this function,
and it has no effect if you do.

%This function sets the version string for the game to the value given by
%{\it version}, which must be a string value.  This function should be called
%once during game initialization to set the game's version string. This string
%is stored in saved game files, and checked when the game is restored; the
%same version of the game must restore a file that saved it, ensuring that
%incompatible files are not restored.
%
%You should be sure to set a different version string in each version of a
%game you release.  To ensure unique version strings, you should use the
%name of your game followed by its version number; for example,
%
%{\example
%    setversion('Space Mission - V2.10');
%}
%
%Without a way of uniquely identifying each game,
%a player could inadvertently restore a
%game from a file saved by an old version of your game; TADS can't tell that
%the files are incompatible, and unpredictable behavior will result.  You
%can ensure that this won't happen by using a unique string in each version
%of a game that you release; when you provide a version string, TADS can
%automatically check to make sure the saved game file was created by the
%same version of the game that is restoring it.  (As described above,
%this was only true in older versions of TADS.  The new system
%automatically generates a unique version identifier for your game
%whenever it is compiled, eliminating the need for you to do this
%manually with the {\tt setversion} function.)

\minorsection{substr}

Call:  {\tt ^{substr}({\it string}, {\it offset}, {\it length})}

This function returns the substring of {\it string} starting at the character
position given by {\it offset} (the first character's position is 1)
and containing up to {\it length} characters.
For example, {\tt substr('abcdefghi', 4, 3)} returns the string {\tt 'def'}.
If the given {\it offset} is past the end of {\it string}, a null string
is returned; hence, {\tt substr('abcdef', 10, 3)} returns a null string.
(Note that a null string, specified by two single quotes, {\tt ''}, is
{\it not} the same as {\tt nil}.)  If the {\it string} is too short to
satisfy the requested {\it length}, the substring from the given {\it offset}
to the end of the {\it string} is returned; for example, {\tt substr(
'abcdefg', 4, 10 )} returns the string {\tt 'defg'}.

\minorsection{undo}

Call:  {\tt ^{undo}()}

This function undoes all changes made since the last ``savepoint'' in
the undo records.  A savepoint is entered at the beginning of each
turn automatically by the player command parser.  Calling {\tt undo()}
once restores the game to its state at the very beginning of the current
turn.  Calling {\tt undo()} again returns it to the state at the beginning
of the previous turn, and so forth.

You should call {\tt undo()} once in any situation where you only want
to undo the current turn.  For example, in a routine that gives the player
options after being killed by an action taken on the current turn, you'd
only want to call {\tt undo()} once if the player elects to undo the
action that killed him, since it's just the current turn that needs to
be taken back.

You should call {\tt undo()} twice in your verb that implements an
``undo'' command, if you have one in your game.  The first call undoes
the current turn (the ``undo'' command itself), and the second call
undoes the previous turn---this is appropriate behavior, since the
``undo'' command should back up one turn.  The default {\tt undoVerb}
defined in {\tt adv.t} implements exactly this behavior.

The {\tt undo()} function returns {\tt true} if the undo operation
was successful, or {\tt nil} if no more undo information is
available.  A return value of {\tt nil} means either that the
player has already undone turns all the way back to the beginning
of the game, or that he has undone turns as far back as the undo
records go.  The default undo area size will hold about a hundred
turns in a typical game, but the actual number of turns that can
be undone will vary by game, depending on the amount of work that needs
to be undone.  The undo mechanism will always keep as many of the most
recent turns as possible, discarding the oldest turns in the undo log
when it runs out of space.


\minorsection{unnotify}

Call:  {\tt ^{unnotify}({\it object}, \&{\it message})}

This function cancels the effect of a previous call to {\tt ^{notify}()} with
the same {\it object} and {\it message}.  Note that the {\tt ^{\&}} before
{\it message} is required.

See also the {\tt notify()} function.

\minorsection{upper}

Call: {\tt ^{upper}({\it string})}

This function returns a copy of {\it string} with all of the lower-case
letters converted to upper-case. Do not confuse this function with the
{\tt caps()} built-in function, which affects only the next character
displayed.

\minorsection{yorn}

Call:  {\tt ^{yorn}()}

Waits for the user to type a character, and returns {\tt 1} if the player
typed ``Y", {\tt 0} if the player typed ``N", and {\tt -1} for anything else.
A suitable prompt should be issued prior
to calling this function.


% If we're making long pages, we'll have to put in a bit of a kludge to fill
% out the final page correctly to make sure the quotation goes in the
% right place.
\ifdim\vsize=44pc \else \vskip 3in \fi


\endchapter

Our life is frittered away by detail$\ldots$
Simplify, simplify.
\author HENRY DAVID THOREAU, {\sl Where I Lived, and What I Lived For\/} (1854)

\bigskip

The statements was interesting but tough.
\author MARK TWAIN, {\sl Adventures of Huckleberry Finn\/} (1884)

\eject
