Chapter 10: Compiler Directives
Compiler directives are top-level instructions processed at compile time. They define program structure, declare data, configure compilation, and control conditional inclusion. Unlike statements (which appear inside routines), directives appear at the outermost level of source files, with a few exceptions noted in §10.12.
Directives are not case-sensitive. The following declarations are equivalent:
Global varname;
GLOBAL varname;
global varname;
Directives may optionally be written with a # prefix:
varname;
For top-level directives, the # is optional. However, the small set of
directives permitted inside routines and object definitions (§10.12) must use
the # prefix.
10.1 Data Definition Directives
10.1.1 Constant
The Constant directive defines a named compile-time constant. It has several
forms:
Constant MAX_ITEMS; ! defines MAX_ITEMS with value 0
Constant MAX_ITEMS = 20; ! defines with an explicit value
Constant MAX_ITEMS 20; ! equivalent (= is optional)
Constant TOTAL = MAX_ITEMS * 3; ! computed from a constant expression
Multiple constants may be declared in a single directive,separated by commas:
Constant NORTH = 1, SOUTH = 2, EAST = 3, WEST = 4;
A constant cannot normally be redefined: a second Constant directive for the
same name produces a compiler error, regardless of whether the value matches.
Constant DEBUG; ! first definition (value 0)
! Constant DEBUG; ! ERROR: name already in use
! Constant DEBUG = 1; ! ERROR: name already in use
To make a constant defined only when not already defined elsewhere, use the
Default directive (see §10.1.4). To explicitly remove a previous definition so
the name can be reassigned, use the Undef directive (see §10.9.1); after
Undef, a subsequent Constant declaration for the same name is accepted:
Constant GAME_VERSION = 1;
Undef GAME_VERSION;
Constant GAME_VERSION = 2; ! now GAME_VERSION is 2
Constants defined with no value are typically used as flags to be tested with
#Ifdef (see §10.5.1).
10.1.2 Global
The Global directive declares a global variable. See §3.1 for a full
discussion of global variable storage and limits.
Global turn_count; ! initialized to 0
Global score = 100; ! initialized to 100
Global score 100; ! equivalent (= is optional)
It is safe to declare a global variable more than once. At most one declaration should give an initial value. Providing the same compile-time constant value in multiple declarations is also accepted.
[Z-machine] The Z-machine provides exactly 240 global variable slots. Seven are reserved by the compiler for internal use, leaving 233 for user-declared globals.
[Glulx] Glulx places no fixed upper bound on the number of global variables; they are allocated dynamically.
10.1.3 Array
The Array directive declares an array. See §8 for full documentation of array
types, initializers, and access patterns.
Array inventory -> 20;
Array exits --> 50;
Array title string "Zork";
Array scores table 0 0 0 0 0;
Array input_buffer buffer 120;
Array flags static -> 1 0 1 0;
10.1.4 Default
The Default directive defines a constant only if it has not already been
defined. This is the primary mechanism by which library files provide default
values that games can override.
Default MAX_CARRIED 100;
Default AMUSING_PROVIDED 0;
If the name is already defined (whether by Constant, as a routine name, or any
other symbol), the Default directive has no effect. A typical pattern is:
! In the game file (compiled first):
Constant MAX_CARRIED 10;
! In a library file (included later):
Default MAX_CARRIED 100; ! no effect - MAX_CARRIED is already 10
10.2 Object and Class Directives
10.2.1 Object
The Object directive declares an object. See §7.1 for the full syntax and
detailed discussion.
Object lamp "brass lamp" study
with name 'brass' 'lamp',
description "A well-polished brass lamp.",
has light;
10.2.2 Nearby
The Nearby directive is equivalent to Object ->. It places the new object as
a child of the most recently declared object at the previous nesting level.
Object study "Study";
Nearby desk "oak desk"
with name 'oak' 'desk',
description "A sturdy desk.";
Nearby chair "wooden chair"
with name 'wooden' 'chair';
This is equivalent to:
Object study "Study";
Object -> desk "oak desk" ...;
Object -> chair "wooden chair" ...;
10.2.3 Class
The Class directive declares a class. See §7.6 for the full syntax and §7.7
for the inheritance rules.
Class Treasure(10)
with value 0,
description "A precious treasure.",
has scored;
10.2.4 Attribute
The Attribute directive declares a boolean attribute that can be assigned to
objects with the has keyword and tested at runtime with has and hasnt.
Attribute light;
Attribute edible;
Attribute locked alias lockable; ! alias for an existing attribute
The alias form creates a second name for an existing attribute. Both names
refer to the same underlying bit.
[Z-machine] The Z-machine (version 4 and later) supports up to 48 attributes (numbered 0-47). Z-machine version 3 supports only 32. The compiler and library reserve some of these.
[Glulx] The number of attributes is controlled by the
$NUM_ATTR_BYTESsetting. The default is 7 bytes (56 attributes), but this can be increased.
10.2.5 Property
The Property directive declares a common property. There are several forms:
Property door_dir; ! common property, no default
Property capacity 100; ! common property with default value
Property additive describe; ! additive: inherited values accumulate
Property individual preference; ! individual property
Property door_dir alias door_to; ! alias for an existing property
The additive keyword causes a property's values to accumulate through the
inheritance chain rather than being overridden. The library uses this for
properties such as name.
The individual keyword declares a property that is stored per object rather
than in the common property table. Individual properties have no default value
and cannot be combined with additive - the compiler rejects that combination
with an explicit error ('individual' incompatible with 'additive'). The
alias keyword likewise does not apply to an individual property (an
individual declaration is processed and finishes before any alias clause
would take effect).
The long keyword is accepted for backward compatibility but has no effect on
the output. Using it produces an obsolete-usage warning.
[Z-machine] The Z-machine (version 4 and later) allows up to 63 common properties (numbered 1-63). Slots
2(the class-inheritance table) and3(the instance-variables table) are reserved by the compiler for internal use, leaving 61 common properties available for use. Slot1isname, which the compiler predeclares as a built-in additive property; the standard library does not declare it. (Z-machine version 3 supports only 29 common properties.)
10.3 Source Organization Directives
10.3.1 Include
Use the Include directive to insert the contents of another source file at the
current location in the source.
Include "Parser"; ! searches include path
Include ">MyExtras"; ! searches same directory as current file
The ">" prefix tells the compiler to look for the file in the same directory
as the main source file (the one named on the command line) - not the directory
of whichever included file the Include directive appears in. Without it, the
compiler searches each directory specified by the +include_path command-line
option (or, if that option is empty, looks up the bare filename through the
operating system, which typically resolves to the current working directory).
Files are included textually: the effect is as if the contents of the included
file replaced the Include directive.
10.3.2 Link
The Link directive was formerly used to link precompiled modules. This
directive now produces a compiler error.
Link "module"; ! ERROR in compiler 6.40+
10.3.3 Replace
The Replace directive allows a routine defined later in the compilation
process (typically in a library file) to be replaced with a new definition.
Replace DrawStatusLine;
[ DrawStatusLine;
! Custom status line drawing code
@set_cursor 1 1;
print "My Custom Status";
];
Include "Parser"; ! the library's DrawStatusLine is ignored
A second form preserves access to the original routine under a new name:
Replace BurnSub OriginalBurnSub;
[ BurnSub;
if (noun == candle) return OriginalBurnSub();
"You shouldn't play with fire.";
];
When multiple definitions of a replaced routine exist, the last-defined version
in a normal file takes precedence. Definitions in System_file files and the
veneer are only used if no normal-file definition exists.
10.3.4 Stub
The Stub directive creates a minimal do-nothing routine if no routine with
that name has been defined. The routine takes a specified number of local
variables (0-4) and returns false.
Stub AfterLife 0;
Stub ChooseObjects 2;
Stub is used by the library to provide default entry points. If the game
defines its own version of the routine, the stub is not created.
10.3.5 System_file
The System_file directive marks the current source file as a system file (a
library or infrastructure file, rather than game author code).
System_file;
This affects how errors and warnings are reported: the compiler may suppress or
reformat messages originating from system files. It also affects Replace
precedence (§10.3.3): definitions in system files are overridden by definitions
in normal files.
10.4 Compilation Configuration
10.4.1 Release
The Release directive sets the release number stored in the story file header.
Release 7;
The release number is a single integer. It does not affect compilation but is embedded in the output file for version-tracking purposes.
10.4.2 Serial
The Serial directive sets the six-character serial number stored in the story
file header. By default, the compiler uses the current date in YYMMDD format.
Serial "250115"; ! must be exactly 6 digits in a string
10.4.3 Statusline
The Statusline directive controls the format of the status line displayed by
the interpreter.
Statusline score; ! show score and turns (default)
Statusline time; ! show the time of day
This directive sets a flag in the story file header. Its effect depends on the interpreter honoring the flag.
10.4.4 Version
The Version directive sets the Z-machine version number for the output file.
Version 5; ! compile for Z-machine version 5
Valid values are 3, 4, 5, 6, 7, and 8. This directive generates a deprecation
warning; the preferred method is the -v command-line switch or !% -v5 header
comment.
[Z-machine] This directive applies only to Z-machine compilation. It has no effect when compiling for Glulx.
10.4.5 Switches
The Switches directive passes command-line switch options from within the
source file.
Switches v5s; ! equivalent to command-line -v5 -s
This directive is deprecated and generates a warning. Use !% header comments
instead:
!% -v5
!% -s
The Switches directive must appear before the first constant or routine
definition.
10.5 Conditional Compilation
Conditional compilation directives control which sections of source code are compiled by evaluating conditions at compile time. They can be nested up to 32 levels deep.
Every opening directive (Ifdef, Ifndef, Iftrue, Iffalse, IFV3, IFV5)
must be matched by a closing Endif directive. The Endif directive takes
no arguments and is terminated by ; like any other directive. An Ifnot
directive (see §10.5.3) may optionally appear once between the opening directive
and its Endif to introduce an "else" branch.
10.5.1 Ifdef and Ifndef
Ifdef compiles a block only if a named symbol is defined. Ifndef is the
inverse.
DEBUG;
[ DebugPrint txt;
print (string) txt, "^";
];
;
CUSTOM_BANNER;
[ Banner;
print "Welcome to the game!^";
];
;
The tested symbol can be any identifier: a constant, a global variable, a routine name, an object, a class, or an attribute. The test checks only whether the symbol has been defined at the point of the directive.
A special pseudo-symbol of the form VN_nnnn is recognized by Ifdef and
Ifndef for testing the compiler version: VN_nnnn is considered defined when
the compiler version number is at least nnnn. Compiler version numbers use the
form 1644 for Inform 6.44, 1640 for 6.40, and so on. VN_nnnn is not a real
symbol and cannot be referenced in any other context.
VN_1640;
! Code requiring compiler 6.40 or later
;
10.5.2 Iftrue and Iffalse
Iftrue compiles a block when a constant expression evaluates to a nonzero
(true) value. Iffalse compiles when the expression evaluates to zero (false).
MAX_ITEMS > 50;
Array large_inventory --> MAX_ITEMS;
;
WORDSIZE == 2;
! This code is only compiled on Glulx (WORDSIZE is 4).
Global extra_data;
;
The expression must be evaluable at compile time, using only constants, compiler-defined symbols, and arithmetic operators.
10.5.3 Ifnot
Ifnot provides an else-branch for any conditional directive. It must appear
between the opening Ifdef/Ifndef/Iftrue/Iffalse/IFV3/IFV5 and the
closing Endif.
TARGET_ZCODE;
! Z-machine-specific code
Constant HEADER_SIZE 64;
;
! Glulx-specific code
Constant HEADER_SIZE 36;
;
Each conditional block may contain at most one Ifnot.
10.5.4 IFV3 and IFV5
IFV3 compiles a block only when targeting Z-machine version 3.
;
! V3-only code (e.g., limited status line handling)
;
;
! V4+ and Glulx code
;
Despite its name, IFV5 does not restrict compilation to version 5
specifically. It covers all versions from 4 onward, including Glulx. The name is
a historical artifact. IFV3 is equivalent to:
TARGET_ZCODE;
( <= 3);
! ...
;
;
10.5.5 Nesting and Scope
Conditional directives can be nested up to 32 levels deep:
TARGET_ZCODE;
( >= 5);
DEBUG;
! Z-code v5+ debug-only code
;
;
;
Conditional compilation is one of the few directive categories that can appear
inside routines and object definitions when prefixed with # (see §10.12):
[ MyRoutine;
print "Starting...^";
DEBUG;
print "[Debug mode active]^";
;
rfalse;
];
10.6 Text and Character Directives
10.6.1 Abbreviate
The Abbreviate directive declares a text string to be used for Z-machine text
compression. Abbreviations are only created when the economy (-e) switch is
active; without it, the directive is silently skipped.
Abbreviate "the ";
Abbreviate "You ";
Abbreviate "ing ";
Abbreviations reduce the size of the encoded text in the story file. The compiler substitutes frequently occurring strings with compact tokens.
[Z-machine] The number of abbreviations is controlled by
$MAX_ABBREVS. The hard ceiling is 96, but$MAX_ABBREVSand$MAX_DYNAMIC_STRINGSmust sum to exactly 96, so raising one requires lowering the other (their defaults are 64 and 32). Abbreviation strings may be of any length (earlier compiler versions limited them to 64 characters).
[Glulx] The
Abbreviatedirective has no effect when compiling for Glulx, which uses a different text encoding.
10.6.2 Lowstring
The Lowstring directive defines an encoded string placed in low memory (the
same pool used by the abbreviations table, near the start of the story file).
Lowstring MyText "Hello, world!";
The constant MyText holds the byte address of the string divided by 2. On
Z-machine version 3, packed string addresses are also computed as byte addresses
divided by 2, so MyText is itself a packed string address and can be printed
directly:
print (string) MyText; ! Z-machine v3 only
On Z-machine versions 4 and later, packed string addresses use a larger scale
factor (4 in v4-7, 8 in v8), so MyText is not a packed address.
print (string) MyText would misdecode the address. To print the string by its
byte address, multiply by 2 and use print (address):
print (address) (2 * MyText); ! Z-machine v4+
Lowstring is rarely needed; it exists for backward compatibility with
Inform 5. The more common approach for dynamic string references is the string
statement.
[Z-machine]
Lowstringis supported only on the Z-machine.
[Glulx]
Lowstringis not supported on Glulx.
10.6.3 Zcharacter
The Zcharacter directive customizes the Z-character alphabet table used to
encode text in the story file, and (in one form) configures additional
parser-terminating characters.
Zcharacter 'ä'; ! Add a character to the alphabet
Zcharacter "abcdefghijklmnopqrstuvwxyz" ! redefine all three alphabet rows
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"0123456789.,!?_#'/@{5c}-:()";
Zcharacter table 'a' 'b' 'c'; ! define the ZSCII-to-Unicode table
Zcharacter table + '@{e9}' '@{e8}'; ! Add to the existing table
Zcharacter terminating 129 130; ! add input-terminating ZSCII codes
The five forms are:
- Single character (
Zcharacter 'c') - adds one character to the Z-character alphabet so that it encodes more compactly. - Three alphabet strings - redefines the three rows of the Z-character
alphabet table from scratch. The first two strings (alphabets A0 and A1) must
each contain exactly 26 characters; the third (A2) must contain exactly 23
characters and fills positions 3-25 of A2 (positions 0 and 1 are fixed by the
Z-machine standard, and the compiler fixes position 2 to hold the tilde
character). A literal backslash is written with the Unicode escape
@{5c}, since a bare\inside a string is a line-continuation marker rather than a character. See §1.1.4. tableform - defines the ZSCII-to-Unicode mapping for ZSCII codes 155 onward (the extra-character range).table +form - appends to the existing ZSCII-to-Unicode mapping rather than replacing it.terminatingform - declares additional ZSCII codes that terminate a keyboard input read (in addition to the default Enter, ZSCII 13). Up to 32 such codes may be declared. The terminating-characters table is emitted to the story file only when targeting Z-machine version 5 or later; on versions 3 and 4, the directive is silently ignored. See §1.1.4.
Characters not in the alphabet require multi-byte escape sequences when encoded into Z-machine text.
[Z-machine]
Zcharacterapplies only to Z-machine text encoding.
[Glulx]
Zcharacteris not supported when compiling for Glulx (the compiler reports an error); Glulx uses Unicode strings natively.
10.7 Dictionary and Action Directives
10.7.1 Dictionary
The Dictionary directive forces a word into the dictionary and optionally sets
flag values. See §9.6 for full dictionary documentation.
Dictionary 'plugh'; ! add word with no special flags
Dictionary 'xyzzy' 128; ! add word and set dict_par1 flag
Dictionary 'abracadabra' 128 4; ! set both dict_par1 and dict_par3
If the word already exists, the flag values are bitwise-OR'd with the existing
flags. This directive cannot set the dict_par2 field (verb number).
[Z-machine] Flag values must be in the range 0-255 (one byte).
[Glulx] Flag values must be in the range 0-65535 (two bytes).
10.7.2 Verb and Extend
The Verb directive defines verb grammar, and Extend modifies existing
grammar. These are documented fully in Part 3 (the parser and grammar system).
Verb 'take' 'get'
* noun -> Take
* 'off' worn -> Disrobe;
Extend 'take'
* 'inventory' -> Inv;
Two Verb declarations for the same word are accepted (equivalent to
Extend last), but this usage generates a warning. The Extend form is
preferred.
10.7.3 Fake_Action
The Fake_Action directive declares a fake action. Fake actions have action
numbers but no associated grammar - they cannot be triggered by player input.
They are used for before/after hooks and internal signaling.
Fake_Action Salute;
Object guard "guard"
with before [;
Salute: "The guard salutes you back!";
];
A fake action can be sent to an object using the action-invocation syntax:
<Salute guard>;
10.8 Informational Directives
10.8.1 Message
The Message directive prints a message during compilation. It does not affect
the compiled output.
Message "Compiling the main game file...";
Message warning "This feature is experimental.";
Message error "Missing required constant STORY_NAME.";
Message fatalerror "Cannot continue without STORY_NAME.";
The warning form issues a compiler warning. The error form issues a
non-fatal error (compilation continues, but no output file is produced). The
fatalerror form halts compilation immediately.
Message can be used inside routines with the # prefix (see §10.12):
[ Init;
"Compiling Init routine...";
location = study;
];
10.8.2 Trace
The Trace directive adjusts trace and diagnostic settings during compilation.
The compiler-side $! trace settings (see Appendix D and Appendix E for the
full 18-option set) are generally preferred for configuring the same trace
levels from the command line or a header comment. Still, the directive form is
not formally deprecated and emits no warning. It retains the unique ability to
print tables and to change trace levels partway through compilation.
The directive recognizes a fixed set of trace keywords, defined in the
compiler's trace_keywords group:
| Keyword | Effect |
|---|---|
assembly |
Set the assembly-trace level (also the default if no keyword is given) |
expressions |
Set the expression-tree trace level |
tokens |
Set the token-lexing trace level |
dictionary |
Print the dictionary table at this point in compilation |
objects |
Print the object tree at this point in compilation |
symbols |
Print the symbol table (Trace symbols 2 adds compiler-defined symbols) |
verbs |
Print the verb-grammar table at this point in compilation |
lines |
Recognized but not implemented (warning emitted) |
linker |
Recognized but not implemented (warning emitted) |
on / off |
Modifiers used after a trace keyword to enable (level 1) or turn off (level 0) it |
Examples:
Trace dictionary; ! print dictionary as of this point
Trace objects; ! print object tree as of this point
Trace symbols; ! print symbol table
Trace symbols 2; ! ...with compiler-defined symbols too
Trace verbs; ! print the grammar table as of this point
Trace assembly on; ! enable assembly tracing
Trace assembly off; ! turn off assembly tracing
Trace expressions 2; ! set expression trace to level 2
Trace tokens on; ! enable token tracing
The bare form Trace; and the numeric form Trace N; are both equivalent to
Trace assembly N; (with N defaulting to 1).
Inside the compiler, the larger family of 18 $! trace options ($!ACTIONS,
$!ASM, $!BPATCH, $!DICT, $!EXPR, $!FILES, $!FINDABBREVS, $!FREQ,
$!MAP, $!MEM, $!OBJECTS, $!PROPS, $!RUNTIME, $!STATS, $!SYMBOLS,
$!SYMDEF, $!TOKENS, $!VERBS) covers strictly more diagnostic categories -
including several (memory map, abbreviation frequencies, action listings) that
the directive form cannot reach. New code should generally prefer the $!
settings; see Appendix D for full details.
10.8.3 Origsource
The Origsource directive marks the following source lines as having originated
from a different file, primarily for tools that generate code from other
languages (such as Inform 7).
Origsource "story.ni" 42 1; ! lines from story.ni, line 42, char 1
! ... generated code ...
Origsource; ! reset to current file position
The declaration holds until the next Origsource directive but does not apply
to included files. Error messages and debug output will reference the declared
source location rather than the actual I6 file position.
10.9 Symbol Management
10.9.1 Undef
The Undef directive removes a previously defined constant.
Constant BETA_TEST;
! ... code that uses #Ifdef BETA_TEST ...
Undef BETA_TEST;
! ... from here, #Ifdef BETA_TEST will be false ...
Undef only works on constants defined with Constant. It cannot undefine
globals, routines, objects, or other symbol types. If the named constant was
never defined, the directive does nothing.
Keep in mind that both Constant declarations and Undef directives take
effect only from the point where they appear. A constant is not defined before
its declaration, and it remains defined until an Undef directive is
encountered.
10.10 End Directive
The End directive marks the end of the source file. Everything after End; is
ignored by the compiler.
[ Main;
print "Hello!^";
];
End;
The compiler completely ignores this text.
It could be notes, design documents, or anything.
End is rarely used explicitly, since reaching the physical end of the source
file has the same effect.
10.11 Import
The Import directive was formerly part of the module-linking system, which
allowed precompiled modules to share symbols. This directive produces a compiler
error.
10.12 Directives Allowed Inside Routines
Most directives can only appear at the top level of a source file, outside
routine and object definitions. The following directives may also appear inside
routines and object bodies when prefixed with #:
- Conditional compilation:
#Ifdef,#Ifndef,#Iftrue,#Iffalse,#Ifnot,#Endif,#IFV3,#IFV5 - Informational:
#Message,#Trace - Source tracking:
#Origsource
The # prefix is mandatory in this context. Omitting it produces a compiler
error.
Object torch "torch"
with description [;
print "A wooden torch";
LIT_DESCRIPTIONS;
if (self has light) print " (lit)";
;
".";
],
BURNABLE;
before [;
Burn: give self light; "You light the torch.";
],
;
has ;
Inside routines, these directives are most commonly used for conditional compilation of platform-specific or debug code:
[ MovePlayer dest;
DEBUG;
print "[Moving player to ", (name) dest, "]^";
;
PlayerTo(dest);
MAX_ITEMS > 100;
CheckEncumbrance();
;
];