Chapter 32: Menus, Multimedia, and Extended Features
This chapter covers the library's support for status line customization, interactive menus, sound and graphics, file I/O, and undo. These features span a range of complexity and virtual machine support: some, like status line customization and undo, work on both the Z-machine and Glulx with minor differences; others, like file I/O, are available only on Glulx. Where a feature differs between virtual machines, the relevant sections are marked with [Z-machine] or [Glulx] tags.
32.1 Status Line Customization
The status line is the top line of the display and conventionally shows the
current location name, score, and move count. The library draws it automatically
every turn, but a game can fully customize its content and layout by replacing
the DrawStatusLine routine.
32.1.1 The sline1 and sline2 Globals
Two global variables control the values displayed on the right side of the default status line:
Global sline1; ! score (or hours, for timed games)
Global sline2; ! moves (or minutes, for timed games)
By default, the library updates these at the end of every turn:
sline1is set to the currentscore(or the hours component ofthe_timeif the game uses a real-time clock).sline2is set to the currentturns(or the minutes component ofthe_time).
The Statusline time; directive (see §10.4.3) switches the library from
score/moves mode to time-of-day mode. When this directive is active, the right
side of the status line displays hours and minutes rather than score and moves.
This is independent of the real-time clock mechanism described in §22.7 - the
Statusline directive only controls display formatting, not actual timekeeping.
A game can set sline1 and sline2 directly at any point to override the
displayed values. This is most commonly done in an Initialise or in an
each_turn entry point to show custom information.
32.1.2 The Default DrawStatusLine Routine
The library defines the default DrawStatusLine routine. Its behavior depends
on the virtual machine and, for the Z-machine, on the Z-machine version number.
[Z-machine] On Z-machine version 3, the status line is drawn by the
interpreter itself, not by the game. The game communicates values to the
interpreter through header bytes: the interpreter reads the current room name,
score/time values, and the statusline-is-time flag from fixed locations in the
story file header. The DrawStatusLine routine in the library therefore does
nothing on V3 beyond setting these header values. The Z-machine specification
requires interpreters to display a status line in V3, but its precise formatting
is interpreter-dependent.
[Z-machine] On Z-machine version 4 and later (V4/V5/V7/V8), the game is responsible for drawing its own status line. The default implementation proceeds as follows:
@split_window 1- creates a one-line upper window for the status line.@set_window 1- switches output to the upper window.@set_cursor 1 1- positions the cursor at the top-left corner (1-based coordinates).style reverse- enables reverse video for the status bar appearance.- The routine prints spaces across the full screen width (obtained via
ScreenWidth()) to create a solid reverse-video bar. @set_cursor 1 1- repositions to the start of the line.- The location name is printed on the left.
- The score/moves or time display is printed on the right, right-justified by computing column positions from the screen width.
style roman- restores normal text style.@set_window 0- switches output back to the main (lower) window.
The opcodes used - @split_window, @set_window, @set_cursor, @set_font -
are documented in §27.
[Glulx] On Glulx, DrawStatusLine uses the library's own
platform-abstraction helpers rather than calling Glk directly. The library
maintains a global gg_statuswin that holds the Glk window reference for the
status window (created during initialization by GGInitialise). The default
implementation (parser.h:6499-6572):
- Calls
StatusLineHeight()to size the status window, thenMoveCursor(1, 1)to position at the top-left. (MoveCursorinternally callsglk_window_move_cursor(gg_statuswin, col-1, row-1)with 0-based Glk coordinates.) - Uses
ScreenWidth()to obtain the window width. - Clears the previous contents by printing
spaces width- it does not callglk_window_clear. - Calls
MoveCursor(1, 2)and prints the location name on the left. - Computes column offsets and calls
MoveCursoragain to right-justify the score/moves or time display. - Calls
MainWindow()to return output to the main window. (MainWindowinternally callsglk_set_window(gg_mainwin).)
(glk_window_clear and glk_set_style(style_Subheader) are used by the Glulx
DoMenu implementation, not by DrawStatusLine.)
For details on Glk windows and styles, see §28.8.
32.1.3 Screen Utility Routines
The library provides several platform-abstracted screen utility routines that
are used internally by DrawStatusLine and the menu system, and are available
for game code:
ClearScreen(window) - clears the specified window. On the Z-machine, it
switches on window and issues the matching @erase_window opcode -
@erase_window -1 for WIN_ALL, @erase_window 1 for WIN_STATUS, and
@erase_window 0 for WIN_MAIN (the Z-machine operands are not the same as the
abstract constant values). On Glulx, it calls glk_window_clear() on the
appropriate Glk window. The window parameter uses the constants defined in
parser.h:390-392: WIN_ALL = 0 (all windows), WIN_STATUS = 1 (status window
only), WIN_MAIN = 2 (main window only).
MoveCursor(line, column) - positions the cursor to the given line and
column within the upper (status) window. Coordinates are 1-based:
MoveCursor(1, 1) is the top-left corner. On the Z-machine, this compiles to
@set_cursor line column. On Glulx, it calls
glk_window_move_cursor(gg_statuswin, column-1, line-1), adjusting for Glk's
0-based coordinates.
MainWindow() - switches output back to the main (lower) window. On the
Z-machine, this compiles to @set_window 0. On Glulx, it calls
glk_set_window(gg_mainwin).
ScreenWidth() - returns the width of the screen in characters.
[Z-machine] On the Z-machine, ScreenWidth reads the screen width from
header byte $21 (address 33 decimal):
[ ScreenWidth;
return (HDR_SCREENWCHARS->0);
];
[Glulx] On Glulx, ScreenWidth queries the current window's dimensions via
glk_window_get_size - the status window while the status line is being drawn
(when statuswin_current is set), otherwise the main window:
[ ScreenWidth id;
id = gg_mainwin;
if (gg_statuswin && statuswin_current) id = gg_statuswin;
glk_window_get_size(id, gg_arguments, 0);
return gg_arguments-->0;
];
32.1.4 Replacing DrawStatusLine
To provide a custom status line, use the Replace directive (see §30.1) to
override the library's default implementation. The replacement routine must
handle all windowing and cursor positioning itself.
The following example shows a typical custom status line for V5+ Z-code games:
Replace DrawStatusLine;
[ DrawStatusLine width;
@split_window 1;
@set_window 1;
@set_cursor 1 1;
style reverse;
width = ScreenWidth();
spaces width;
@set_cursor 1 1;
print " ", (name) location;
@set_cursor 1 (width - 20);
print "Score: ", sline1, " Moves: ", sline2;
style roman;
@set_window 0;
];
A portable replacement that works on both Z-machine and Glulx should use conditional compilation:
Replace DrawStatusLine;
[ DrawStatusLine width;
TARGET_ZCODE;
@split_window 1;
@set_window 1;
@set_cursor 1 1;
style reverse;
width = ScreenWidth();
spaces width;
@set_cursor 1 1;
print " ", (name) location;
@set_cursor 1 (width - 20);
print "Score: ", sline1, " Moves: ", sline2;
style roman;
@set_window 0;
; ! TARGET_GLULX
if (gg_statuswin == 0) return;
glk_set_window(gg_statuswin);
width = ScreenWidth();
glk_window_clear(gg_statuswin);
glk_window_move_cursor(gg_statuswin, 0, 0);
print " ", (name) location;
glk_window_move_cursor(gg_statuswin, width - 22, 0);
print "Score: ", sline1, " Moves: ", sline2;
glk_set_window(gg_mainwin);
;
];
You can create a multi-line status line by splitting the window into two or more
lines. On the Z-machine, change the argument to @split_window:
Replace DrawStatusLine;
[ DrawStatusLine width;
@split_window 2;
@set_window 1;
width = ScreenWidth();
style reverse;
@set_cursor 1 1; spaces width;
@set_cursor 2 1; spaces width;
@set_cursor 1 1;
print " ", (name) location;
@set_cursor 1 (width - 20);
print "Score: ", sline1;
@set_cursor 2 1;
print " ", (string) narrative_description;
@set_cursor 2 (width - 20);
print "Moves: ", sline2;
style roman;
@set_window 0;
];
Multi-line status bars consume screen real estate and reduce the space available for main text. On small-screen interpreters (particularly V3 terminals), large status bars may be impractical.
32.1.5 Status Line and the Game Loop
The library calls DrawStatusLine at the start of every turn, just after
printing the prompt (see §16.4 for the main game loop). This means any changes
to sline1, sline2, or any other global used by a custom DrawStatusLine
will be reflected on the next turn. To force an immediate redraw mid-turn (for
example, after a score change), call DrawStatusLine() explicitly.
32.2 Menu Systems
The library includes a built-in menu system that can display hierarchical menus of information to the player. This is most commonly used for in-game help systems, "about" pages, and hint menus. The menu system adapts its interface to the interpreter's capabilities: on capable interpreters it uses a windowed, cursor-addressed display; on minimal interpreters it falls back to numbered text menus.
32.2.1 The DoMenu Entry Point
The main entry point is DoMenu(menu_choices, EntryR, ChoiceR), which
dispatches to an appropriate menu implementation based on the virtual machine
and interpreter capabilities.
Parameters:
menu_choices- either a string or a routine, printed once as the body of the menu below the title. It is not a^-separated label string that the library parses: whenmenu_choicesis a routine, that routine prints the visible list of choices itself (the library does not render the per-item labels in the list); when it is a plain string, only that string is shown.EntryR- a routine that supplies the title and the per-item labels (each shown as the header of a chosen item's content page).ChoiceR- a routine that prints the content of a chosen item.
Both callback routines are called with no arguments. They communicate with the library through global variables rather than parameters:
- Before calling
EntryR, the library sets the globalmenu_item:- When
menu_itemis0,EntryRmust return the number of menu items and set the globalitem_nameto the menu's title (and, optionally,item_widthto the title's width). - When
menu_itemis1to N,EntryRmust setitem_nameto that item's label (and optionallyitem_width). In this case, it ignores the return value.
- When
- When the player selects an item, the library puts the chosen item number in
menu_itemand callsChoiceR, which prints the content for that choice and returns a control code:2= redisplay the menu,3= exit the menu and return to the game,- any other value = remain in the menu.
32.2.2 Using DoMenu
The following example demonstrates a complete help menu system:
[ HelpMenuEntry;
switch (menu_item) {
0: item_name = "Help Menu"; return 3; ! title; 3 items follow
1: item_name = "About this game";
2: item_name = "How to play";
3: item_name = "Credits";
}
];
[ HelpMenuChoice;
switch (menu_item) {
1: print "This is a demonstration game.^";
2: print "Type commands to interact with the world.^";
3: print "Written by the author.^";
}
return 2; ! redisplay the menu after showing the text
];
[ HelpSub;
DoMenu("Select a topic, then read it. Choose Quit to return.",
HelpMenuEntry, HelpMenuChoice);
];
To make this accessible, define a verb:
Verb meta 'help' 'info'
* -> Help;
The menu title comes from item_name as set by EntryR when menu_item is
0, and the number of selectable items is the value EntryR returns in that
same call. The string passed as menu_choices ("Select a topic..." here) prints
as the menu's descriptive body, not as item labels. Because this menu_choices
is a plain string, the three choices are not themselves listed on screen - the
player selects by number (the fallback prompt reads "Type a number from 1 to
3...") or by moving the > cursor. To show a labelled list, pass a routine
for menu_choices that prints the numbered options; EntryR's labels are used
only as the header above each chosen item's content.
32.2.3 The LowKey_Menu Fallback
LowKey_Menu(menu_choices, EntryR, ChoiceR) provides a text-only menu fallback.
It is used automatically on Z-machine V3 (which has no upper window support) and
on interpreters that lack cursor-addressing capabilities. Game code can also
call it directly when it wants a simple numbered-choice interface.
The routine works as follows:
- Calls
EntryRwithmenu_item = 0to obtain the item count and the title, then prints the title. - Prints the descriptive body (the
menu_choicesstring, or the result of calling it if it is a routine). - Prompts the player with
>and reads a full line of input. - If the line is empty or its first word is a quit word (e.g.
quit,q), the menu exits. - Otherwise it parses the first word as a number with
TryNumber. Entering0redisplays the menu (re-running the entry callback); a non-numeric word (for whichTryNumberreturns a negative sentinel) or an out-of-range number re-prompts. - For a valid item number, it sets
menu_itemand callsChoiceR, whose return code then controls whether the menu redisplays (2), exits (3), or loops.
This implementation requires no special interpreter capabilities - it works with plain sequential text output and ordinary line input.
32.2.4 Z-machine Windowed Menu
[Z-machine] On V4 and later, DoMenu uses a graphical windowed menu that
takes over the full screen. The implementation proceeds through several phases:
Screen setup:
@erase_window $ffffclears all windows, resetting to a blank screen.@split_window heightcreates an upper window large enough to display the menu items plus a title bar and navigation instructions.@set_window 1directs output to the upper window.
Menu rendering:
- The title is printed centred at the top of the upper window using
@set_cursorfor positioning. - The current selection is marked with a
>character printed beside its line; moving the highlight prints>on the new line and erases the previous marker with a space. (style reverseis applied only to the title and navigation-key bar, not to the menu items themselves.) - The upper window is split tall enough to hold every item at once
(
@split_windowuseslines+7), so the list is not broken into pages and no page indicators are shown.
Input handling:
-
@read_char 1reads a single keypress without echoing it. -
Navigation keys:
- N or Down arrow - move highlight to the next item.
- P or Up arrow - move highlight to the previous item.
- Return/Enter - select the highlighted item, calling
ChoiceR. - Q or Escape - exit the menu and return to the game.
Navigation wraps rather than paging: pressing N on the last item moves the highlight back to the first, and P on the first item moves it to the last.
Selection display: When the player selects an item, the lower window is used
to display the full content returned by ChoiceR. The player presses a key to
return to the menu listing.
Cleanup: When the player exits the menu (Q or Escape), the routine restores the normal screen layout:
@erase_window $ffffclears both windows.@set_window 0returns output to the main (lower) window.- A
<Look>action is generated to redisplay the current room; the game loop on the following turn redraws the one-line status bar.
32.2.5 Glulx Menu
[Glulx] The Glulx menu implementation uses the Glk API for all display operations. The structure mirrors the Z-machine version but uses Glk calls:
Window management:
glk_window_clear(gg_mainwin)clears the main window.glk_set_window(gg_statuswin)selects the status window for menu drawing.glk_window_get_size(gg_statuswin, gg_arguments, gg_arguments+4)obtains the window dimensions for layout calculations.glk_window_move_cursor(gg_statuswin, x, y)positions text within the status window for each menu item.
Styling:
glk_set_style(style_Subheader)is used for the menu title and the navigation-key bar, not for the menu items (the highlighted item is a>marker printed instyle_Normal).glk_set_style(style_Normal)is used for the item list (highlighted or not) and the body text.
Input:
KeyCharPrimitive()handles input through the Glk event system, callingglk_request_char_event()and waiting for aevtype_CharInputevent. This provides the same single-keypress interface as@read_charon the Z-machine.
Cleanup: On exit, the routine clears the main window
(glk_window_clear(gg_mainwin)) and generates a <Look> action to restore the
room description; the game loop redraws the status line on the next turn.
32.2.6 Menu Design Considerations
As shown above, DoMenu does not pack item labels into a single
^-separated string, and it does not render the option list from EntryR
either. EntryR supplies the title (when menu_item is 0) and, for
menu_item 1 to N, the label shown as the header above that item's
content once the item is chosen. The visible list of options is produced by
menu_choices: a routine menu_choices prints the numbered choices itself,
while a plain string is shown as-is (so the player moves the > cursor over
choices the game code must have listed). A few practical points follow from
this:
- Labels should be short enough to fit on one line; the menu system does not wrap long labels.
- The number of items is whatever
EntryRreturns whenmenu_itemis0, so a menu's length is bounded only by what that callback enumerates. - There is no automatic pagination: the menu window is split tall enough to hold
every item at once (
lines+7lines), and the highlight wraps from the last item back to the first rather than turning a page.
For complex multi-level menus, ChoiceR can call DoMenu recursively to create
nested submenus. Like EntryR, ChoiceR is called with no arguments and
inspects the menu_item global to learn which entry was chosen. Each level of
nesting pushes a new menu onto the screen, and exiting returns to the parent:
[ TopMenuChoiceR;
switch (menu_item) {
1: DoMenu("Choose a command category to read about.",
SubMenuEntry, SubMenuChoiceR);
2: print "This game was created as a demonstration.^";
}
return 2; ! redisplay the parent menu afterward
];
32.3 Sound and Graphics
Both the Z-machine and Glulx support sound effects and graphical images, but through entirely different mechanisms. Z-machine multimedia is accessed through dedicated opcodes, while Glulx uses the Glk API. In both cases, the game must be packaged with resource files containing the actual sound and image data (typically in a Blorb archive).
32.3.1 Z-machine Sound and Graphics
[Z-machine] Sound effects are available from V3 onward. Graphics are restricted to V6 (the graphical version of the Z-machine, rarely used in practice).
Sound effects:
The @sound_effect opcode plays, stops, or manages sound resources:
@sound_effect number effect volume routine
| Parameter | Description |
|---|---|
number |
Sound resource number (indexes into the Blorb sound resources). |
effect |
Operation: 1 = prepare, 2 = start, 3 = stop, 4 = finish all. |
volume |
Volume level: 1-8 (1 = quietest, 8 = loudest), or -1 for maximum. On V5+, the operand is a single word: the low byte holds the volume (1-8), and the high byte holds the number of repeats (0 = once, 255 = loop forever). When you need only volume, pass the value directly (1-8). |
routine |
Callback routine address (V5+ only), called when the sound finishes playing. Pass 0 for no callback. |
Examples:
! Play sound resource 3 at volume 8, no callback
@sound_effect 3 2 8 0;
! Stop sound resource 3
@sound_effect 3 3;
! Play with a completion callback (V5+)
@sound_effect 5 2 6 SoundDone;
Not all interpreters support sound. Games should degrade gracefully when sound
is unavailable: the Z-machine specification does not provide a standard
capability query for sound in versions before V5. In V5+, the header flags byte
at address $01 indicates interpreter capabilities, but sound support flags are
not universally reliable.
Graphics (V6 only):
V6 provides opcodes for drawing and managing pictures:
@draw_picture pic_num y x- draws picturepic_numat position (y,x) in the current window. Coordinates are in screen units (pixels in most V6 interpreters).@erase_picture pic_num y x- erases the area occupied by picturepic_numat the given position, filling it with the background color.@picture_data pic_num array ?label- a branch opcode. It stores the height and width of picturepic_numintoarray-->0andarray-->1, respectively (ifpic_numis 0, the number of available pictures and the release number of the picture file instead), and branches tolabelwhen the picture data is available.@picture_table table- hints to the interpreter that the pictures listed intable(a word array of picture numbers, terminated by 0) should be preloaded into memory for fast display.
! Draw picture 1 at the top-left corner
@draw_picture 1 1 1;
! Query picture dimensions
Array pic_info --> 2;
@picture_data 1 pic_info ?pic_exists;
jump no_pic;
.pic_exists;
print "Height: ", pic_info-->0,
" Width: ", pic_info-->1, "^";
.no_pic;
! Preload pictures 1-3
Array preload_pics --> 1 2 3 0;
@picture_table preload_pics;
V6 games are uncommon because few interpreters fully support the V6 graphical model. Most modern games targeting graphical output use Glulx instead.
32.3.2 Glulx Sound and Graphics
[Glulx] Glulx provides sound and graphics through the Glk API. Unlike the Z-machine's dedicated opcodes, Glk uses an object-oriented model with windows, streams, and channels.
Capability checking:
Before using multimedia features, a game should query the interpreter's
capabilities using glk_gestalt(). The relevant gestalt constants are:
| Constant | Value | Meaning |
|---|---|---|
gestalt_Graphics |
6 | Can the interpreter display graphics at all? |
gestalt_DrawImage |
7 | Can images be drawn in the specified window type? |
gestalt_Sound |
8 | Can the interpreter play sounds? |
gestalt_SoundVolume |
9 | Does the interpreter support volume control? |
gestalt_SoundNotify |
10 | Does the interpreter send sound completion events? |
gestalt_Sound2 |
21 | Does the interpreter support the Sound2 extension (MOD, OGG)? |
Usage:
if (glk_gestalt(gestalt_Graphics, 0) == 0) {
print "This interpreter cannot display graphics.^";
}
if (glk_gestalt(gestalt_Sound, 0) == 0) {
print "This interpreter cannot play sounds.^";
}
The second argument to glk_gestalt() is a subquery parameter. For
gestalt_DrawImage, pass the window type constant (e.g., wintype_TextBuffer
or wintype_Graphics) to check whether images can be drawn in that specific
window type.
Graphics functions:
glk_image_draw(win, image, val1, val2)- draws image resourceimagein windowwin. For text buffer windows,val1andval2control alignment. For graphics windows, they specify the x,y position.glk_image_draw_scaled(win, image, val1, val2, width, height)- draws the image scaled to the specified
widthandheightin pixels.
- draws the image scaled to the specified
glk_image_get_info(image, width_ptr, height_ptr)- retrieves the dimensions of imageimage, storing the width and height at the given addresses. Returns true if the image exists.
Example of drawing an image:
[ ShowImage img win width height;
if (glk_gestalt(gestalt_DrawImage, wintype_TextBuffer) == 0) return;
if (glk_image_get_info(img, gg_arguments, gg_arguments+4)) {
width = gg_arguments-->0;
height = gg_arguments-->1;
glk_image_draw(win, img, imagealign_MarginLeft, 0);
}
];
Sound channel functions:
Glk plays sound through sound channels. A game creates one or more channels, then plays sounds through them:
glk_schannel_create(rock)- creates a new sound channel. Therockis an arbitrary identifier for the channel. Returns the channel reference, or 0 on failure.glk_schannel_play(chan, sound)- plays sound resourcesoundon channelchan. Returns true on success.glk_schannel_play_ext(chan, sound, repeats, notify)- extended play:repeatsis the number of times to play (1 = once, -1 = loop forever), andnotifyis a non-zero value that will be included in the sound notification event when playback completes.glk_schannel_stop(chan)- stops any sound currently playing onchan.glk_schannel_set_volume(chan, vol)- sets the volume forchan. Volume is a linear scale where$10000(65536) is full volume, and 0 is silence.glk_sound_load_hint(sound, flag)- hints to the interpreter that sound resourcesoundshould be preloaded (flag= 1) or may be unloaded (flag= 0). The interpreter may ignore this hint.
Complete sound example:
Global background_channel;
[ InitSound;
if (glk_gestalt(gestalt_Sound, 0) == 0) return;
background_channel = glk_schannel_create(210);
];
[ PlaySound snd chan;
if (glk_gestalt(gestalt_Sound, 0) == 0) return;
chan = glk_schannel_create(0);
if (chan) glk_schannel_play(chan, snd);
];
[ PlayBackgroundMusic snd;
if (background_channel == 0) return;
! Loop the music indefinitely
glk_schannel_play_ext(background_channel, snd, -1, 0);
glk_schannel_set_volume(background_channel, $8000); ! 50% volume
];
[ StopBackgroundMusic;
if (background_channel) glk_schannel_stop(background_channel);
];
Sound notification events:
If glk_gestalt(gestalt_SoundNotify, 0) returns true, the interpreter sends an
evtype_SoundNotify event when a sound finishes playing (only if a non-zero
notify value was passed to glk_schannel_play_ext). The event's val2 field
contains the notification value. Games can handle this in their HandleGlkEvent
entry point (see §24.27) to trigger actions when sounds complete.
32.3.3 Blorb Resource Packaging
Both Z-machine and Glulx games reference sounds and images by numeric resource ID. The actual media data is typically stored in a Blorb archive - a container format that bundles the game file with its resources. The Blorb file maps resource numbers to embedded data chunks (AIFF or OGG for sounds, PNG or JPEG for images).
The compiler does not create Blorb archives directly. A separate tool, such as
bres or iblorb, combines the compiled game file with resource files into a
single .zblorb (Z-machine) or .gblorb (Glulx) package.
Resource numbering must be consistent between the Blorb manifest and the resource IDs used in game code. By convention, picture resources start at 1, and sound resources also start at 1; the Blorb format distinguishes them by chunk type.
32.4 File I/O (Glulx)
[Glulx] The Glk API provides a complete file I/O system, allowing Glulx games to read and write external files. This capability has no equivalent on the Z-machine, which supports only saving and restoring game state. File I/O supports persistent data storage, inter-game communication, transcript output, and command recording.
32.4.1 File Mode and Usage Constants
File operations use mode and usage constants:
File mode constants control how a file is opened:
| Constant | Value | Description |
|---|---|---|
filemode_Write |
1 | Open for writing; truncates existing file. |
filemode_Read |
2 | Open for reading only. |
filemode_ReadWrite |
3 | Open for both reading and writing. |
filemode_WriteAppend |
5 | Open for writing; appends to existing file. |
File usage constants describe the type of file:
| Constant | Value | Description |
|---|---|---|
fileusage_Data |
0 | General-purpose data file. |
fileusage_SavedGame |
1 | Saved game state (used by save/restore). |
fileusage_Transcript |
2 | Transcript output file. |
fileusage_InputRecord |
3 | Recorded command input file. |
fileusage_TextMode |
256 | Text mode (line-ending conversion). Combine with ` |
fileusage_BinaryMode |
0 | Binary mode (no conversion). This is the default. |
The usage and mode values are combined with the bitwise OR operator. For
example, fileusage_Data | fileusage_TextMode opens a general-purpose text file
with platform-appropriate line-ending conversion.
32.4.2 File References
Before opening a file, a file reference (fileref) must be created. A fileref represents a file's identity on the host system without opening it. There are three ways to create a fileref:
glk_fileref_create_by_prompt(usage, mode, rock) - prompts the player to
specify a filename through the interpreter's native file dialog. This is the
recommended method for any file the player should know about, as it respects the
interpreter's sandboxing and file access policies. Returns 0 if the player
cancels.
glk_fileref_create_by_name(usage, name, rock) - creates a fileref with a
specific filename. The interpreter may modify the filename for security reasons
(adding extensions, restricting to a safe directory). Not all interpreters
support this; those that do may restrict the path.
glk_fileref_create_temp(usage, rock) - creates a fileref for a temporary
file. The interpreter chooses the filename and location. The file is deleted
when the fileref is destroyed or the game exits.
In all cases, the rock parameter is an arbitrary identifier you can use to
find the fileref later through iteration.
After use, filerefs should be destroyed with glk_fileref_destroy(fref) to
release the associated system resource. Destroying a fileref does not delete the
underlying file or close any stream opened from it.
If you want to verify that a file is present before trying to read it, call
glk_fileref_does_file_exist(fref). This function returns true when the file
indicated by fref is available on the host system.
32.4.3 Stream Operations
Files are accessed through streams, which provide a uniform I/O interface. The stream operations are:
Opening streams:
glk_stream_open_file(fileref, mode, rock)- opens the file identified byfilerefin the given mode. Returns a stream reference, or 0 on failure.glk_stream_open_memory(buf, buflen, mode, rock)- opens a memory buffer as a stream. Useful for in-memory string construction and formatting.bufis a byte array,buflenis its length.
Closing streams:
glk_stream_close(stream, result_ptr)- closes the stream. Ifresult_ptris non-zero, the read and write counts are stored at that address.
Positioning:
glk_stream_set_position(stream, pos, seekmode)- sets the read/write position.seekmodeis 0 for absolute, 1 for relative to current position, 2 for relative to end.glk_stream_get_position(stream)- returns the current position in the stream.
Reading and writing:
glk_put_char_stream(stream, ch)- writes a single character.glk_put_string_stream(stream, str)- writes a string.glk_put_buffer_stream(stream, buf, len)- writeslenbytes frombuf.glk_get_char_stream(stream)- reads a single character. Returns -1 at end of file.glk_get_buffer_stream(stream, buf, len)- reads up tolenbytes intobuf. Returns the number of bytes actually read.glk_get_line_stream(stream, buf, len)- reads a line (up tolenbytes) intobuf. Returns the number of bytes read.
Current stream:
glk_stream_set_current(stream)- sets the current output stream. From that point onward, every print statement will be sent to this stream. This is the Glulx equivalent of the Z-machine's@output_streamopcode. To restore normal output, set the current stream back to the main window's stream.
32.4.4 Complete File I/O Example
The following example demonstrates writing data to a file and reading it back:
[ SaveData fref str;
fref = glk_fileref_create_by_prompt(
fileusage_Data | fileusage_TextMode,
filemode_Write, 0);
if (fref == 0) rfalse;
str = glk_stream_open_file(fref, filemode_Write, 0);
glk_fileref_destroy(fref);
if (str == 0) rfalse;
glk_put_string_stream(str, "saved data here");
glk_stream_close(str, 0);
rtrue;
];
Reading data back:
Array read_buffer -> 256;
[ LoadData fref str len;
fref = glk_fileref_create_by_prompt(
fileusage_Data | fileusage_TextMode,
filemode_Read, 0);
if (fref == 0) rfalse;
if (glk_fileref_does_file_exist(fref) == 0) {
glk_fileref_destroy(fref);
rfalse;
}
str = glk_stream_open_file(fref, filemode_Read, 0);
glk_fileref_destroy(fref);
if (str == 0) rfalse;
len = glk_get_buffer_stream(str, read_buffer, 256);
glk_stream_close(str, 0);
! Process read_buffer contents (len bytes read)
rtrue;
];
32.4.5 The Glk Wrapper and Output Streams
The veneer includes Glk__Wrap, a wrapper routine that mediates between the
print statement and the Glk I/O system. When the compiler targets Glulx, it
routes all print output through the current Glk stream. The @glk opcode
provides direct access to the Glk API; the veneer function translates between
the compiler's calling convention and the Glk dispatch layer.
On the Z-machine, @output_stream directs output to different destinations
(screen, transcript, table, or command file). On Glulx, this is accomplished
entirely through Glk stream management:
Z-machine @output_stream |
Glulx equivalent |
|---|---|
| Stream 1 (screen) | glk_set_window(gg_mainwin) - output to main window. |
| Stream 2 (transcript) | Open a file stream and set it as the current stream. |
| Stream 3 (table) | glk_stream_open_memory() - capture output to a buffer. |
| Stream 4 (command file) | Open a file stream with fileusage_InputRecord. |
32.5 Undo Support
The undo mechanism allows the player to reverse the most recent turn, restoring the complete game state to what it was before the last command. Both the Z-machine and Glulx provide hardware-level undo through save/restore-state opcodes, and the library integrates undo into the standard game loop.
32.5.1 Undo Opcodes
[Z-machine] The Z-machine provides two opcodes for undo (available from V5 onward):
-
@save_undo -> result(EXT opcode 0x09) - saves a snapshot of the entire game state (memory, stack, program counter) into an interpreter-managed buffer. The result is:- 1 if the save succeeded.
- 0 if the save failed this turn (for example, the interpreter ran out of
memory) - the library maps this to
undo_flag = 1. - -1 if the interpreter does not support undo at all - the library maps this
to
undo_flag = 0. - 2 if the interpreter has just restored from this undo point (i.e.,
control has returned here after a
@restore_undo).
-
@restore_undo -> result(EXT opcode 0x0A) - restores the game state from the most recently saved undo snapshot. If successful, execution resumes where@save_undowas called, with the result variable set to 2. If unsuccessful, execution continues normally, and the result is 0.
[Glulx] Glulx provides equivalent opcodes with slightly different result conventions:
-
@saveundo result- saves a state snapshot. Returns 0 on success, 1 on failure, and -1 when control returns after a restore. -
@restoreundo result- restores from the most recent snapshot. On success, execution resumes at the@saveundopoint. On failure, returns 1.
The result conventions differ between the two virtual machines. The library code accounts for this with conditional compilation, translating the Glulx return values to match the library's internal convention.
32.5.2 Library Undo Globals
The library maintains two global variables to track undo state:
Global undo_flag;
Global just_undone;
undo_flag records the current availability of undo:
| Value | Meaning |
|---|---|
| 0 | The interpreter does not support undo at all. |
| 1 | Undo is temporarily unavailable (the last save attempt failed, possibly due to memory pressure). |
| 2 | Undo is available - a valid undo snapshot exists. |
just_undone is set to 1 immediately after a successful undo and reset to 0
at the start of the next turn. Its name suggests it flags consecutive undo
attempts, but in library 6.12.8 the flag is written but never read: neither
PerformUndo nor the game loop tests just_undone, so it does not block a
second undo. (The message string for that case still exists - Miscellany 12 -
but the library never prints it.)
32.5.3 Saving Undo State in the Game Loop
The library saves an undo snapshot every turn as part of the main game loop. This code runs early in each turn - just after the player's command is read but before it is processed - so that the undo point captures the state as it was at the beginning of the turn:
TARGET_ZCODE;
@save_undo i;
; ! TARGET_GLULX
@saveundo i;
if (i == -1) { GGRecoverObjects(); i = 2; }
else i = (~~i);
;
just_undone = 0;
undo_flag = 2;
if (i == -1) undo_flag = 0;
if (i == 0) undo_flag = 1;
This code performs the following steps:
- Save the undo snapshot using the appropriate opcode for the target platform.
- Handle Glulx restore return: on Glulx, when
@saveundoreturns -1, it means the interpreter has just restored to this point (the equivalent of result 2 on the Z-machine). The library callsGGRecoverObjects()to re-establish Glk object references (window IDs, stream handles, etc.) that the state restore may have invalidated, then normalizes the result to 2. - Normalize Glulx results: the
~~i(logical NOT) converts the Glulx convention (0 = success) to the library's convention (non-zero = success). - Reset
just_undoneto 0, allowing undo on this turn. - Set
undo_flagbased on the result:- Result of -1 (Z-machine) →
undo_flag = 0(no undo support). - Result of 0 (Z-machine) →
undo_flag = 1(save failed this turn). - Otherwise →
undo_flag = 2(undo available).
- Result of -1 (Z-machine) →
32.5.4 The PerformUndo Routine
When the player types UNDO, the parser recognizes it as a special meta-command
and calls PerformUndo. This routine handles all the validation and error
reporting:
-
Check for game start: if the turn count is at its initial value (comparing
turnsagainst the starting turn), the undo is rejected with library messageMiscellany11: "[You can'tundowhat hasn't been done!]." -
Check undo availability: if
undo_flagis 0, the undo is rejected with library messageMiscellany6: "[Your interpreter does not provideundo. Sorry!]" Ifundo_flagis 1, the undo is rejected with library messageMiscellany7, whose wording is platform-specific: "[You cannotundoany further.]" on Glulx (the Z-machine text differs - see §32.5.5). -
Attempt restore: the appropriate restore opcode is executed:
TARGET_ZCODE; @restore_undo i; ; ! TARGET_GLULX @restoreundo i; ; -
Handle failure: if the restore opcode returns with a failure result, the message printed depends on the platform (
parser.h:1503-1510):- [Z-machine]
@restore_undoreturns 0 on failure, soi == 0andPerformUndoprintsMiscellany7 and returns 0. - [Glulx]
@restoreundoreturns 1 on failure; because~~is logical NOT,i = (~~i)makesibecome 0, so theif (i == 0)branch is taken andPerformUndoprintsMiscellany7 and returns 0 - the same outcome as the Z-machine path.
- [Z-machine]
On a successful restore, the opcode does not return to PerformUndo at all:
execution resumes at the @save_undo/@saveundo call in the game loop
(§32.5.3), which now reports a "restored" result. The game loop - not
PerformUndo - then handles the success: it reprints the room name, prints
Miscellany message 13 ("[Previous turn undone.]"), and sets
just_undone = 1.
32.5.5 Undo-Related Library Messages
The undo system communicates with the player through the Miscellany library
message set. These can be customized through the standard library message
interception mechanism (see §30.7):
| Message Number | Default Text | When Used |
|---|---|---|
| 6 | "[Your interpreter does not provide |
undo_flag == 0: interpreter lacks undo support entirely. |
| 7 | [Z-machine] "~Undo~ failed. [Not all interpreters provide it.]" / [Glulx] "[You cannot ~undo~ any further.]" (english.h:1130-1134) |
undo_flag == 1: undo save failed this turn; or the restore opcode returned failure (both VMs). |
| 11 | "[You can't |
Player tries to undo before the first move. |
| 12 | "[Can't |
Defined but unused: library 6.12.8 never prints this message (the just_undone flag that would trigger it is never tested). |
| 13 | "[Previous turn undone.]" | Successful undo restoration. |
The tilde characters (~) in these messages are the language's escape sequence
for double-quote characters in strings (see §1.6.2).
32.5.6 Dictionary Words for UNDO
The words that the parser recognizes as the UNDO command are defined in
english.h as dictionary word constants:
Constant UNDO1__WD = 'undo';
Constant UNDO2__WD = 'undo';
Constant UNDO3__WD = 'undo';
All three constants point to the same word by default. A language definition file for another language can redefine these to provide up to three synonyms for the undo command in the target language (see §31.1 for the language definition file interface).
The parser checks for these words early in its main loop, before full grammar parsing begins, treating UNDO as a special command that bypasses the normal action processing pipeline. This is necessary because undo must restore game state before any turn processing occurs.
32.5.7 Programmatic Undo
A game can invoke undo programmatically by calling PerformUndo() directly.
This is occasionally useful for implementing a "restart last puzzle" mechanic or
an auto-undo triggered by certain events. However, since only one level of undo
state is maintained, calling PerformUndo() more than once between saves will
fail on the second attempt.
A game can also prevent undo on specific turns by setting undo_flag = 0 in a
before or after routine. This causes the next undo attempt to report that
the interpreter does not support undo. To prevent undo globally, set
undo_flag = 0 in the Initialise entry point and again at the start of each
turn (in a TimePasses or each_turn handler) to override the library's
automatic save.
For games that require multi-level undo (more than one turn back), this must be implemented at the application level - for example, by maintaining a stack of serialized game states using the file I/O facilities described in §32.4 (Glulx only).