Chapter 6: Routines
This chapter describes routines (functions): how they are declared, how arguments and local variables work, how values are returned, and the calling conventions that govern their behavior on the Z-machine and Glulx virtual machines.
6.1 Routine Declaration Syntax
A routine is declared with square brackets enclosing a name, an optional list of local variables, and a body of statements:
[ RoutineName local1 local2 ... localN;
statements
];
The opening [ begins the routine. The routine name follows immediately. After
the name comes zero or more local variable names, separated by whitespace. A
semicolon ends the header and begins the body. The closing ] followed by ;
ends the routine.
[ Double x;
return x * 2;
];
Local variable names are untyped - each is a single machine word, just like all values (see §2).
6.2 Stand-Alone Routines
A stand-alone routine (also called a top-level routine) is defined at the outermost level of the source file, outside any object or class definition. It is callable by name from anywhere in the program:
[ Greet;
print "Hello, adventurer!^";
];
[ Main;
Greet();
];
Stand-alone routines are the primary mechanism for organizing code in programs. The name becomes a global constant whose value is the packed address of the routine.
6.3 Embedded Routines
An embedded routine is defined inline as the value of an object or class property. It has no explicit name in the source:
Object lamp "brass lamp"
with description [;
print "A well-polished brass lamp.^";
],
before [;
Take: print "You pick up the lamp carefully.^";
rtrue;
];
The compiler assigns an internal name to each embedded routine, derived from the
enclosing object or class and the property name. For an embedded routine inside
an object's property, the parts are joined by a period, e.g.,
lamp.description; for a class property, they are joined by ::, e.g.,
Container::before. Embedded routines are not callable by name from other parts
of the program - they are invoked automatically by the library when the relevant
property is accessed, or explicitly via obj.prop().
Embedded routines may only appear as the value of an object or class property. They are not accepted as values in arbitrary expressions, in array initializers, or anywhere else a routine value is needed. To use a routine value in those contexts, declare a stand-alone routine and reference it by name.
6.4 Parameters and Local Variables
The local variables listed in a routine's header serve a dual purpose: the first N locals receive the N arguments passed by the caller, and any remaining locals are initialized to zero.
[ Add a b;
return a + b;
];
[ Main result;
result = Add(3, 4); ! a=3, b=4, result is 7
];
6.4.1 Missing and Excess Arguments
If the caller supplies fewer arguments than the routine declares locals, the unmatched locals are initialized to zero:
[ Flexible a b c;
print a, " ", b, " ", c, "^";
];
[ Main;
Flexible(10); ! prints: 10 0 0
Flexible(10, 20); ! prints: 10 20 0
Flexible(10, 20, 30); ! prints: 10 20 30
];
If the caller supplies more arguments than the routine has locals, the excess arguments are silently ignored on the Z-machine. They are evaluated (so side effects occur), but their values are discarded.
6.4.2 Local Variable Limits
On the Z-machine, a routine may declare at most 15 local variables (the
virtual machine's hard limit; the compiler constant MAX_LOCAL_VARIABLES is 16,
which counts the sp pseudo-slot at index 0). On Glulx, the limit is 118
local variables - MAX_LOCAL_VARIABLES is 119, again including sp. Both
limits are fixed compiler constants and are not user-configurable.
6.4.3 Locals Are Not Persistent
Local variables exist only for the duration of a single call. Each invocation of a routine receives its own fresh set of locals. Recursive calls each get independent copies (see §6.10).
6.5 Return Values
Every routine returns a single value to its caller. There are several ways to specify the return value.
6.5.1 Explicit return
The return statement exits the routine immediately with the given value:
[ Max a b;
if (a >= b) return a;
return b;
];
return with no expression returns true (1), regardless of whether the
routine is stand-alone or embedded.
6.5.2 rtrue and rfalse
These shorthand statements return true (1) and false (0) respectively:
[ IsPositive n;
if (n > 0) rtrue;
rfalse;
];
6.5.3 String-as-Statement Shorthand
A bare double-quoted string as a statement is equivalent to print_ret: it
prints the string, prints a newline, and returns true:
[ Blocked;
"You can't go that way.";
! equivalent to: print_ret "You can't go that way.";
];
6.6 The Default Return Convention
When execution reaches the closing ] of a routine without encountering an
explicit return, rtrue, or rfalse, the return value depends on the routine
type:
| Routine type | Default return value |
|---|---|
| Stand-alone | true (1) |
| Embedded | false (0) |
[ StandAlone;
print "Doing work.^";
! falls off the end & returns true
];
Object thing "thing"
with before [;
print "Before.^";
! falls off the end & returns false
];
This convention exists because the library interprets return values from
embedded property routines as "should the default action be suppressed?"
Returning false means "no, continue with the default", which is the safe
default for embedded routines. Stand-alone routines, by contrast, often
represent actions that "succeed" by default.
Tip: Always use explicit return statements in non-trivial routines. Relying on the implicit default makes code harder to understand.
6.7 Calling Conventions
6.7.1 Argument Passing
Arguments are passed by value. The caller evaluates each argument expression and places the results in the callee's local variables. Changes to local variables inside the routine do not affect the caller's variables:
[ Increment x;
x = x + 1;
print x, "^";
];
[ Main n;
n = 5;
Increment(n); ! prints 6
print n, "^"; ! prints 5 - n is unchanged
];
6.7.2 Z-Machine Argument Limit
On the Z-machine (versions 4 and later), a single call instruction can pass at most 7 arguments. Attempting to call a routine with more than 7 arguments produces a compile-time error. Z-machine version 3 is even more restrictive, allowing at most 3 arguments per call. The Z-machine also limits routines to a total of 15 local variables (parameters plus non-parameter locals).
6.7.3 Glulx Argument Limit
On Glulx, the argument limit is significantly higher and is effectively constrained only by available stack space. This makes Glulx suitable for routines that need many parameters.
6.7.4 Return Value Handling
Every call expression produces a value - the routine's return value if the
caller does not use the return value (e.g., a bare MyRoutine(); expression
statement), the value is discarded.
6.8 indirect() and Indirect Calls
The built-in function indirect() calls a routine whose address is stored in a
variable or expression. The first argument is the routine address; subsequent
arguments are passed to the called routine:
[ Apply fn x;
return indirect(fn, x);
];
[ Double n;
return n * 2;
];
[ Main result;
result = Apply(Double, 21);
print result, "^"; ! prints 42
];
6.8.1 Use Cases
Indirect calls are useful for:
- Callback patterns - passing behavior as an argument.
- Dispatch tables - storing routine addresses in arrays and calling them by index.
- Plugin architectures - swapping behavior at runtime.
Array handlers --> ProcessA ProcessB ProcessC;
[ Dispatch n arg;
return indirect(handlers-->n, arg);
];
6.8.2 Argument Limits for indirect()
On the Z-machine (versions 4 and later), indirect() supports the routine
address plus up to 6 call arguments (7 operands in total). This is one fewer
than a direct call, where the routine address plus 7 call arguments are allowed.
On version 3 the limit drops to 3 call arguments, the same cap that applies to
direct calls. The compiler generates different call opcodes depending on the
number of arguments.
6.9 Variable-Argument Routines (Glulx)
On Glulx, a routine can accept a variable number of arguments by naming its
first parameter _vararg_count. When the compiler sees this special name, it
generates code that passes arguments on the VM stack rather than in fixed local
variable slots:
[ PrintAll _vararg_count val;
while (_vararg_count > 0) {
@copy sp val;
print val, " ";
_vararg_count--;
}
new_line;
];
[ Main;
PrintAll(10, 20, 30); ! prints: 10 20 30
PrintAll(1); ! prints: 1
];
6.9.1 How It Works
When a _vararg_count routine is called:
- All arguments are pushed onto the Glulx stack.
_vararg_countis set to the number of arguments actually passed.- The routine body uses
@copy sp localvar(Glulx assembly) to pop arguments from the stack one at a time.
6.9.2 Z-Machine Limitation
This mechanism is Glulx-only. The Z-machine has no equivalent; on the Z-machine, the number and identity of arguments are fixed at compile time by the routine's local variable list.
6.10 Recursion
Routines may recurse fully. A routine may call itself directly or indirectly, and each call receives its own set of local variables on the virtual machine's stack:
[ Factorial n;
if (n <= 1) return 1;
return n * Factorial(n - 1);
];
[ Main;
print "5! = ", Factorial(5), "^"; ! prints: 5! = 120
];
6.10.1 Stack Depth
Each recursive call consumes additional stack space, so the total stack usage grows with the depth of recursion. On the Z-machine, stack space is limited (typically a few hundred frames, depending on the story file format and interpreter). Deep recursion can exhaust the stack and cause a runtime error.
On Glulx, the stack is generally much larger, but extremely deep recursion can still overflow it.
6.10.2 Tail Recursion
The compiler does not perform tail-call optimization. A recursive call in tail position still allocates a new stack frame. If deep recursion is needed, consider rewriting the algorithm iteratively:
[ FactorialIter n result;
result = 1;
for (: n > 1 : n--)
result = result * n;
return result;
];
6.11 Routine References as Values
Because a routine name is a compile-time constant holding the routine's packed address, routines can be stored in variables, passed as arguments, and placed in arrays:
[ Hello;
print "Hello!^";
];
[ Main fn;
fn = Hello;
indirect(fn); ! calls Hello
];
6.11.1 Identifying Routines with metaclass
The metaclass() built-in function can determine whether a value is a routine:
[ Identify val;
if (metaclass(val) == Routine)
print "It's a routine.^";
else if (metaclass(val) == Object)
print "It's an object.^";
else if (metaclass(val) == Class)
print "It's a class.^";
else if (metaclass(val) == String)
print "It's a string.^";
else
print "It's nothing special.^";
];
The four metaclasses - Routine, Object, Class, and String - cover all
non-integer values. An integer (including zero) returns nothing (0) from
metaclass().
6.11.2 Routine References in Properties
A common pattern stores routine references in object properties for later invocation:
[ DefaultReact;
"Nothing happens.";
];
[ SpecialReact;
"Something amazing happens!";
];
Object widget "widget"
with react_fn DefaultReact;
[ TriggerReaction obj;
indirect(obj.react_fn);
];
[ Main;
TriggerReaction(widget); ! "Nothing happens."
widget.react_fn = SpecialReact;
TriggerReaction(widget); ! "Something amazing happens!"
];
6.11.3 Routine References in Arrays
Dispatch tables are a natural use of routine references:
[ HandleNorth; print "You go north.^"; ];
[ HandleSouth; print "You go south.^"; ];
[ HandleEast; print "You go east.^"; ];
[ HandleWest; print "You go west.^"; ];
Array direction_handlers -->
HandleNorth HandleSouth HandleEast HandleWest;
[ GoDirection dir;
if (dir >= 0 && dir < 4)
indirect(direction_handlers-->dir);
else
print "Invalid direction.^";
];
6.12 The Replace Directive
The Replace directive lets a later definition supersede an earlier one for a
named routine. It is the standard mechanism for overriding a routine supplied by
an included library or extension. Replace must appear before the file
containing the original definition is included.
6.12.1 One-Argument Form
Replace RoutineName;
This form tells the compiler to drop the definition of RoutineName provided by
an included library file, so that a subsequent definition of RoutineName in
the user's own source becomes the symbol's value. The original (included) body
is silently dropped from the compiled output, and references elsewhere in the
program are routed to the replacement.
Replace InScope; ! discard the library's InScope
Include "Parser";
Include "VerbLib";
[ InScope actor;
! ... custom scope routine ...
];
6.12.2 Two-Argument Form
Replace RoutineName OriginalName;
The two-argument form is the same as the one-argument form except that the original (replaced) routine remains callable under the second name. This is useful when the new definition wants to delegate to or extend the original behavior rather than discarding it entirely.
Replace DrawStatusLine OriginalDrawStatusLine;
Include "Parser";
Include "VerbLib";
[ DrawStatusLine;
! Pre-processing of the status line
OriginalDrawStatusLine();
! Post-processing of the status line
];
The original-form symbol becomes available as a routine constant holding the packed address of the original definition; calling it behaves exactly like calling the original routine.
6.12.3 Replacing System Functions
Replace can also be applied to a small set of built-in system functions (such
as random) that are normally implemented by the virtual machine. In this case,
only the one-argument form is permitted, and the directive must appear before
the system function is referenced anywhere in the program; otherwise, the
compiler reports You can't 'Replace' a system function already used.
6.12.4 Restrictions
Replacemust precede the original definition; if the named symbol has already been defined, the compiler reports an error of the formExpected name of routine not yet defined but found ....- The original symbol must be a routine, not a constant, object, or other declaration.
- A given routine may not be
Replaced under two different new names (using the two-argument form), nor may a name already used as the first argument of oneReplacebe used as the second argument of another. Issuing the one-argumentReplacefor the same routine more than once is harmless and has no additional effect.