Limbo is a new programming language, designed by Sean Dorward, Phil Winterbottom, and Rob Pike. Limbo borrows from, among other things, C (expression syntax and control flow), Pascal (declarations), Winterbottom's Alef (abstract data types and channels), and Hoare's CSP and Pike's Newsqueak (processes). Limbo is strongly typed, provides automatic garbage collection, supports only very restricted pointers, and compiles into machine-independent byte code for execution on a virtual machine.
This paper is an introduction to Limbo. Since Limbo is an integral part of the Inferno system, the examples here illustrate not only the language but also a certain amount about how to write programs to run within Inferno.
Disclaimer: I'm no expert on Limbo, so take this with a grain of salt. And some of this may be wrong because Limbo is still evolving. So is this introduction; comments and suggestions for improvement are welcome.
This document is a quick look at the basics of Limbo; it is not a replacement for the reference manual. The first section is a short overview of concepts and constructs; subsequent sections illustrate the language with examples. Although Limbo is intended to be used in Inferno, which emphasizes networking and graphical interfaces, the discussion here begins with standard text-manipulation examples, since they require less background to understand.
At run time, modules are loaded dynamically; the load statement fetches the code and performs run-time type checking. Once a module has been loaded, its functions can be called.
Limbo is strongly typed; programs are checked at compile time, and further when modules are loaded. The Limbo compiler compiles each source file into a machine-independent byte-coded .dis file that can be loaded at run time.
Besides normal block structure within functions, variables may have global scope within a module; module data can be accessed via the module pointer.
byte unsigned, 8 bits int signed, 32 bits big signed, 64 bits real IEEE long float, 64 bits
Limbo also provides Unicode strings, arrays of arbitrary types, lists of arbitrary types, tuples (in effect, unnamed structures with unnamed members of arbitrary types), abstract data types or adt's (in effect, named structures with function members as well as data members), reference types (in effect, restricted pointers that can point only to adt objects), and typed channels (for passing objects between processes).
A channel is a mechanism for synchronized communication. It provides a place for one process to send or receive an object of a specific type; the attempt to send or receive blocks until a matching receive or send is attempted by another process. The alt statement selects randomly but fairly among channels that are ready to read or write. The spawn statement creates a new process that, except for its stack, shares memory with other processes. Processes are pre-emptively scheduled by the Inferno kernel. (Inferno processes have much in common with threads in other operating systems.)
Limbo performs automatic garbage collection, so there is no need to free dynamically created objects. Objects are deleted and their resources freed when the last reference to them goes away. In general this release of resources happens immediately (``instant free''); release of cyclic data structures may be delayed.
There are no implicit coercions between types, and only a handful of explicit casts. The numeric types byte, int, etc., can be used to convert a numeric expression, as in
nl := byte 10;
if (expr) stat if (expr) stat else stat while (expr) stat for (expr; expr; expr) stat do stat while (expr) ; return expr ; exit ;
Comments begin with # and extend to the end of the line. There is no preprocessor, but an include statement can be used to include source code, usually module declaration files.
The examples in this section are each complete, in the sense that they will run as presented; I have tried to avoid code fragments that merely illustrate syntax.
The first example is the traditional ``hello, world'', in the file hello.b:
implement Hello;
include "sys.m"; sys: Sys; include "draw.m";
Hello: module { init: fn(ctxt: ref Draw->Context, argv: list of string); };
init(ctxt: ref Draw->Context, argv: list of string) { sys = load Sys Sys->PATH; sys->print("hello, world\n"); }
The module declaration defines the external interface that this module presents to the rest of the world. (This declaration is what would go into a hello.m in a larger example.) In this case, it's a single function named init. Since this module is to be called from a command interpreter (shell), by convention its init function takes two arguments, the graphical context and a list of strings, the command-line arguments, though neither is used here. This is like main in a C program. Essentially all of the other examples begin with this standard code.
Most modules have a more extensive set of declarations; for example, draw.m is 170 lines of constants, function prototypes, and type declarations for graphics types like Point and Rect, and sys.m is 120 lines of declarations for functions like open, read, and print. Most module declarations will also be stored in separate files, conventionally suffixed with .m, so they can be included in other modules.
The last few lines of hello.b are the implementation of the init function, which loads the Sys module, then calls its print function. By convention, each module declaration includes a pathname constant that points to the code for the module; this is the second parameter Sys->PATH of the load statement.
With this much of the language described, we can compile and run this program. On Unix or Windows, the command
$ limbo -g hello.b
$ limbo -g hello.b $ emu Inferno main (pid=6559) interp Initialize Dis: /dis/sh.dis slocum.cs.bell-labs.com$ /usr/bwk/hello hello, world slocum.cs.bell-labs.com$
The following module creates and displays a button with the label ``hello, world'' as shown in the screen shot above.
implement Hello2;
include "sys.m"; sys: Sys; include "draw.m"; draw: Draw; include "tk.m"; tk: Tk;
Hello2: module { init: fn(ctxt: ref Draw->Context, argv: list of string); };
init(ctxt: ref Draw->Context, argv: list of string) { sys = load Sys Sys->PATH; draw = load Draw Draw->PATH; tk = load Tk Tk->PATH;
t := tk->toplevel(ctxt.screen, "");
tk->cmd(t, "button .b -text {hello, world}"); tk->cmd(t, "pack .b"); tk->cmd(t, "update");
sys->sleep(10000); # wait 10 seconds }
The sleep delays exit for 10 seconds so the button can be seen and pressed a few times. In a real application, some action would be bound to pressing the button.
Such actions are handled by setting up a channel from the Tk module to one's own code, and processing the ``events'' that appear on this channel. The function tk->namechan establishes a correspondence between a Limbo channel variable and a channel named as a string in the Tk module. When an event occurs in a Tk widget with a -command option, send causes the string to be sent on the channel and the Limbo code can act on it. In this example, the Limbo code is trivial; it waits for a message, discards the value, and exits. A more realistic example would have a loop that contains a case to process the strings that might appear on the channel.
... t := tk->toplevel(ctxt.screen, "");
cmd := chan of string; tk->namechan(t, cmd, "cmd"); # associate Limbo channel with Tk string tk->cmd(t, "button .b -text {Delete me} -command {send cmd bye}"); tk->cmd(t, "pack .b"); tk->cmd(t, "update");
<- cmd; # wait for something to arrive on channel }
The next example, echo, prints its command-line arguments. Declarations are the same as in the first example, and have been omitted.
# declarations omitted... init(ctxt: ref Draw->Context, argv: list of string) { sys = load Sys Sys->PATH;
argv = tl argv; # skip over program name for (s := ""; argv != nil; argv = tl argv) s += " " + hd argv; if (s != "") # something was stored in s sys->print("%s\n", s[1:]); }
The value nil is the ``undefined'' or ``explicitly empty'' value for non-numeric types.
The operator := combines the declaration of a variable and assignment of a value to it. The type of the variable on the left of := is the type of the expression on the right. Thus, the expression
s := ""
The + and += operators concatenate strings. The expression s[1:] is a slice of the string s that starts at index 1 (the second character of the string) and goes to the end; this excludes the unwanted blank at the beginning of s.
The word count program wc reads its standard input and counts the number of lines, words, and characters. Declarations have again been omitted.
# declarations omitted... init(nil: ref Draw->Context, argv: list of string) { sys = load Sys Sys->PATH; buf := array[1] of byte;
stdin := sys->fildes(0);
OUT: con 0; IN: con 1;
state := OUT; nl := 0; nw := 0; nc := 0; for (;;) { n := sys->read(stdin, buf, 1); if (n <= 0) break; c := int buf[0]; nc++; if (c == '\n') nl++; if (c == ' ' || c == '\t' || c == '\n') state = OUT; else if (state == OUT) { state = IN; nw++; } } sys->print("%d %d %d\n", nl, nw, nc); }
This program contains several instances of the := operator. For example, the line
nl := 0; nw := 0; nc := 0;
A Limbo program starts with three open files for standard input, standard output, and standard error, as in Unix. The line
stdin := sys->fildes(0);
The lines
OUT: con 0; IN: con 1;
Given the declarations of IN and OUT, the line
state := OUT;
The line
buf := array[1] of byte;
buf : array of byte; # no size at declaration buf = array[1] of byte; # size needed at creation
Limbo does no automatic coercions between types, so an explicit coercion is required to convert the single byte read from stdin into an int that can be used in subsequent comparisons with int's; this is done by the line
c := int buf[0];
Warning: The word count program above tacitly assumes that its input is in the ASCII subset of Unicode, since it reads input one byte at a time instead of one Unicode character at a time. If the input contains any multi-byte Unicode characters, this code is plain wrong. The assignment to c is a specific example: the integer value of the first byte of a multi-byte Unicode character is not the character.
There are several ways to address this shortcoming. Among the possibilities are rewriting to use the bufio module, which does string I/O, or checking each input byte sequence to see if it is a multi-byte character. The second version of word counting uses bufio. This example will also illustrate rules for accessing objects within modules.
# declarations omitted... include "bufio.m"; bufmod: Bufio; Iobuf: import bufmod; iob: ref Iobuf;
init(nil: ref Draw->Context, nil: list of string) { sys = load Sys Sys->PATH; bufmod = load Bufio Bufio->PATH; if (bufmod == nil) { sys->print("bufmod load: %r\n"); exit; }
stdin := sys->fildes(0); iob = bufmod->fopen(stdin, bufmod->OREAD); if (iob == nil) { sys->print("iob open: %r\n"); exit; }
OUT: con 0; IN: con 1;
state := OUT; nl := 0; nw := 0; nc := 0; for (;;) { c := iob.getc(); if (c == bufmod->EOF) break; nc++; if (c == '\n') nl++; if (c == ' ' || c == '\t' || c == '\n') state = OUT; else if (state == OUT) { state = IN; nw++; } } sys->print("%d %d %d\n", nl, nw, nc); }
include "bufio.m"; bufmod: Bufio;
Bufio: module # edited to fit your screen { PATH: con "/dis/bufio.dis"; EOF: con -1; Iobuf: adt { fd: ref Sys->FD; # the file buffer: array of byte; # the buffer # other variables omitted getc: fn(b: self ref Iobuf) : int; gets: fn(b: self ref Iobuf, sep: int) : string; close: fn(b: self ref Iobuf); }; open: fn(name: string, mode: int) : ref Iobuf; fopen: fn(fd: ref Sys->FD, mode: int) : ref Iobuf; };
The bufio module defines open and fopen functions that return references to an Iobuf; this is much like a FILE* in the C standard I/O library. A reference is necessary so that all uses refer to the same entity, the object maintained by the module.
Given the name of a module (e.g., Bufio), how do we refer to its contents? It is always possible to use fully-qualified names, and the import statement permits certain abbreviations. We must also distinguish between the name of the module itself and a specific implementation returned by load, such as bufmod.
The fully-qualified name of a type or constant from a module is
Modulename->name
modulehandle->functionname modulehandle->variablename modulehandle->adtname.membername
iob: ref bufmod->Iobuf; ... bufmod->open(...) bufmod->iob.getc() bufmod->iob.fd
An import statement makes a specific list of names from a module accessible without need for a fully-qualified name. Each name must be imported explicitly, and adt member names can not be imported. Thus, the line
Iobuf: import bufmod;
The second parameter of load is the location of the module implementation, typically a .dis file. Some modules are part of the system; these have location names that begin with $ but are otherwise the same for users. By convention, modules include a constant called PATH that points to their default location.
The call to bufmod->fopen attaches the I/O buffer to the already open file stdin; this is rather like freopen in stdio.
The function iob.getc returns the next Unicode character, or bufmod->EOF if end of file was encountered.
A close look at the calls to sys->print shows a new format conversion character, %r, for which there is no corresponding argument in the expression list. The value of %r is the text of the most recent system error message.
This section describes a module that implements a conventional associative array (a hash table pointing to chained lists of name-value strings). This module is meant to be part of a larger program, not a standalone program like the previous examples.
The Hashtab module stores a name-value pair as a tuple of (string, string). A tuple is a type consisting of an ordered collection of objects, each with its own type. The hash table implementation uses several different tuples.
The hash table module defines a type to hold the data, using an adt declaration. An adt defines a type and optionally a set of functions that manipulate an object of that type. Since it provides only the ability to group variables and functions, it is like a really slimmed-down version of a C++ class, or a slightly fancier C struct. In particular, an adt does not provide information hiding (all member names are visible if the adt itself is visible), does not support inheritance, and has no constructors, destructors or overloaded method names. To create an instance of an adt,
adtvar := adtname(list of values for all members, in order); adtvar := ref adtname(list of values for all members, in order);
The Hashtab module contains an adt declaration for a type Table; the operations are a function alloc for initial allocation (in effect a constructor), a hash function, and methods to add and look up elements by name. Here is the module declaration, which is contained in file hashtab.m:
Hashtab: module { PATH: con "/usr/bwk/hashtab.dis"; # temporary name
Table: adt { tab: array of list of (string, string);
alloc: fn(n: int) : ref Table;
hash: fn(ht: self ref Table, name: string) : int; add: fn(ht: self ref Table, name: string, val: string); lookup: fn(ht: self ref Table, name: string) : (int, string); }; };
implement Hashtab;
include "hashtab.m";
Table.alloc(n: int) : ref Table { return ref Table(array[n] of list of (string,string)); }
Table.hash(ht: self ref Table, s: string) : int { h := 0; for (i := 0; i < len s; i++) h = (h << 1) ^ int s[i]; h %= len ht.tab; if (h < 0) h += len ht.tab; return h; }
Table.add(ht: self ref Table, name: string, val: string) { h := ht.hash(name); for (p := ht.tab[h]; p != nil; p = tl p) { (tname, nil) := hd p; if (tname == name) { # illegal: hd p = (tname, val); return; } } ht.tab[h] = (name, val) :: ht.tab[h]; }
Table.lookup(ht: self ref Table, name: string) : (int, string) { h := ht.hash(name); for (p := ht.tab[h]; p != nil; p = tl p) { (tname, tval) := hd p; if (tname == name) return (1, tval); } return (0, ""); }
The hash function is trivial; the only interesting point is the len operator, which returns the number of items in an object. For a string, len s is the number of Unicode characters.
The self declaration says that the first argument of every call of this function is implicit, and refers to the object itself; this argument does not appear at any call site. Self is similar to this in C++.
The lookup function searches down the appropriate list for an instance of the name argument. If a match is found, lookup returns a tuple consisting of 1 and the value field; if no match is found, it returns a tuple of 0 and an empty string. These return types match the function return type, (int, string).
The line
(tname, tval) := hd p;
The add function is similar; it searches the right list for an instance of the name. If none is found,
ht.tab[h] = (name, val) :: ht.tab[h];
The line
(tname, nil) := hd p;
The line
# illegal: hd p = (tname, val);
To create a new Table, add some values, then retrieve one, we can write:
nvtab = Table.alloc(101); # make a Table nvtab.add("Rob", "Pike"); nvtab.add("Howard", "Trickey"); (p, phil) := nvtab.lookup("Phil"); (q, sean) := nvtab.lookup("Sean");
This example presents a simple module based on Awk's input mechanism: it reads input a line at a time from a list of of files, splits each line into an array of NF+1 strings (the original input line and the individual fields), and sets NF, NR, and FILENAME. It comes in the usual two parts, a module:
Awk: module { PATH: con "/usr/bwk/awk.dis";
init: fn(argv: list of string); getline: fn() : array of string; NR: fn() : int; NF: fn() : int; FILENAME: fn() : string; };
implement Awk;
include "sys.m"; sys: Sys; include "bufio.m"; bufio: Bufio; Iobuf: import bufio; iobuf: ref Iobuf;
include "awk.m";
_NR: int; _NF: int; _FILENAME: string; argv: list of string;
init(av: list of string) { argv = tl av; if (len argv == 0) # no args => stdin argv = "-" :: nil;
sys = load Sys Sys->PATH; bufio = load Bufio Bufio->PATH; }
getline() : array of string { t := array[100] of string; fl : list of string;
top: while (argv != nil) { if (_FILENAME == nil) { # advance to next file _FILENAME = hd argv; if (_FILENAME == "-") iobuf = bufio->fopen(sys->fildes(0), bufio->OREAD); else iobuf = bufio->open(_FILENAME, bufio->OREAD); if (iobuf == nil) { sys->print("getline %s: %r\n", _FILENAME); argv = nil; return nil; } }
s := iobuf.gets('\n'); if (s == nil) { iobuf.close(); _FILENAME = nil; argv = tl argv; continue top; }
t[0] = s[0:len s - 1]; _NR++; (_NF, fl) = sys->tokenize(t[0], " \t\n\r"); for (i := 1; fl != nil; fl = tl fl) t[i++] = hd fl; return t[0:i]; } return nil; }
NR() : int { return _NR; } NF() : int { return _NF; } FILENAME() : string { return _FILENAME; }
The tokenize function in the line
(_NF, fl) = sys->tokenize(t[0], " \t\n\r");
This program is a simple-minded text formatter, modeled after fmt, that tests the Awk module:
implement Fmt;
include "sys.m"; sys: Sys; include "draw.m";
Fmt: module { init: fn(nil: ref Draw->Context, argv: list of string); };
include "awk.m"; awk: Awk; getline, NF: import awk;
out: array of string; nout: int; length: int; linelen := 65;
init(nil: ref Draw->Context, argv: list of string) { t: array of string; out = array[100] of string;
sys = load Sys Sys->PATH; awk = load Awk Awk->PATH; if (awk == nil) { sys->print("load awk: %r\n"); return; } awk->init(argv);
nout = 0; length = 0; while ((t = getline()) != nil) { nf := NF(); if (nf == 0) { printline(); sys->print("\n"); } else for (i := 1; i <= nf; i++) { if (length + len t[i] > linelen) printline(); out[nout++] = t[i]; length += len t[i] + 1; } } printline(); }
printline() { if (nout == 0) return; for (i := 0; i < nout-1; i++) sys->print("%s ", out[i]); sys->print("%s\n", out[i]); nout = 0; length = 0; }
Another approach to a formatter is to use one process to fetch words and pass them to another process that formats and prints them. This is easily done with a channel, as in this alternative version:
# declarations omitted... WORD, BREAK, EOF : con iota; wds: chan of (int, string);
init(nil: ref Draw->Context, nil: list of string) { sys = load Sys Sys->PATH; bufmod = load Bufio Bufio->PATH;
stdin := sys->fildes(0); iob = bufmod->fopen(stdin, bufmod->OREAD);
wds = chan of (int, string); spawn getword(wds); putword(wds); }
getword(wds: chan of (int, string)) { while ((s := iob.gets('\n')) != nil) { (n, fl) := sys->tokenize(s, " \t\n"); if (n == 0) wds <-= (BREAK, ""); else for ( ; fl != nil; fl = tl fl) wds <-= (WORD, hd fl); } wds <-= (EOF, ""); }
putword(wds: chan of (int, string)) { wd: int; s: string; for (length := 0;;) { (wd, s) =<- wds; case wd { BREAK => sys->print("\n\n"); length = 0; WORD => if (length + len s > 65) { sys->print("\n"); length = 0; } sys->print("%s ", s); length += len s + 1; EOF => sys->print("\n"); exit; } } }
The operator iota is used in con declarations to produce the sequence of values 0, 1, ....
The channel passes a tuple of (int, string); the int indicates what kind of string is present a real word, a break caused by an empty input line, or EOF.
The spawn statement creates a separate process by calling the specified function; except for its own stack, this process shares memory with the process that spawned it. Any synchronization between processes is handled by channels.
The operator <-= writes an expression to a channel; the operator =<- reads from a channel and assigns to a variable. In this example, getword and putword alternate, because each input word is sent immediately on the shared channel, and no subsequent word is processed until the previous one has been received and printed.
The case statement consists of a list of case values, which must be string or numeric constants, followed by => and associated code. The value * (not used here) labels the default. Multiple labels can be used, separated by the or operator, and ranges of values can appear delimited by to, as in
'a' to 'z' or 'A' to 'Z' =>
Inferno supports a rather complete implementation of the Tk interface toolkit developed by John Ousterhout. In other environments, Tk is normally accessed from Tcl programs, although there are also versions for Perl, Scheme and other languages that call Ousterhout's C code. The Inferno Tk was implemented from scratch, and is meant to be called from Limbo programs. There is a module declaration tk.m and a kernel module Tk.
The Tk module provides all the widgets of the original Tk with almost all their options, the pack command for geometry management, and the bind command for attaching code to user actions. In this implementation Tk commands are written as strings and presented to one function, tk->cmd; Limbo calls this function and captures its return value, which is the string that the Tk command produces. For example, widget creation commands like button return the widget name, so this will be the string returned by tk->cmd.
There is one unconventional aspect: the use of a channel to send events from the interface into the Limbo program. To create a widget, as we saw earlier, one writes
tk->cmd("button .b -text {Push me} -command {send cmd .bpush}");
This is all illustrated in the program below, which
implements a trivial version of Etch-a-Sketch:
implement Etch;
include "sys.m"; sys: Sys; include "draw.m"; draw: Draw; include "tk.m"; tk: Tk;
Etch: module { init: fn(ctxt: ref Draw->Context, argv: list of string); };
init(ctxt: ref Draw->Context, argv: list of string) { sys = load Sys Sys->PATH; draw = load Draw Draw->PATH; tk = load Tk Tk->PATH;
x, y, lastx, lasty: int;
t := tk->toplevel(ctxt.screen, "");
cmd := chan of string; tk->namechan(t, cmd, "cmd"); tk->cmd(t, "canvas .c -height 400 -width 600 -background white"); tk->cmd(t, "frame .f"); tk->cmd(t, "button .f.c -text {Clear} -command {send cmd clear}"); tk->cmd(t, "button .f.d -text {Done} -command {send cmd quit}"); tk->cmd(t, "pack .f.c .f.d -side left -fill x -expand 1"); tk->cmd(t, "pack .c .f -side top -fill x"); tk->cmd(t, "bind .c <ButtonPress-1> {send cmd b1down %x %y}"); tk->cmd(t, "bind .c <Button-1-Motion> {send cmd b1motion %x %y}"); tk->cmd(t, "update");
for (;;) { s := <-cmd; (n, cmdstr) := sys->tokenize(s, " \t\n"); case hd cmdstr { "quit" => exit; "clear" => tk->cmd(t, ".c delete all; update"); "b1down" => lastx = int hd tl cmdstr; lasty = int hd tl tl cmdstr; cstr := sys->sprint(".c create line %d %d %d %d -width 2", lastx, lasty, lastx, lasty); tk->cmd(t, cstr); "b1motion" => x = int hd tl cmdstr; y = int hd tl tl cmdstr; cstr := sys->sprint(".c create line %d %d %d %d -width 2", lastx, lasty, x, y); tk->cmd(t, cstr); lastx = x; lasty = y; } tk->cmd(t, "update"); } }
The program creates a canvas for drawing, a button to clear the canvas, and a button to quit. The sequence of calls to tk->cmd creates the picture and sets up the bindings. The expression
s := <-cmd
Normally, a graphical application is meant to run under
the window manager
wm
as a window that can be managed,
reshaped, etc.
This is best done by calling upon the function
titlebar
in the window library
Wmlib.
Here is the startup code for an implementation of
Othello, adapted from a Java version
by Muffy Barkocy, Arthur van Hoff, and Ben Fry.
init(ctxt: ref Draw->Context, argv: list of string) { sys = load Sys Sys->PATH; draw = load Draw Draw->PATH; tk = load Tk Tk->PATH; wmlib = load Wmlib Wmlib->PATH;
wmlib->init();
tkargs := ""; argv = tl argv; # remove program name if (argv != nil) { # and extract any -geom arg tkargs = hd argv; argv = tl argv; } t = tk->toplevel(ctxt.screen, tkargs+" -borderwidth 2 -relief raised"); menubut := wmlib->titlebar(t, "Othello", Wmlib->Appl);
cmd := chan of string; tk->namechan(t, cmd, "cmd"); tk->cmd(t, "canvas .c -height 400 -width 400 -background green"); tk->cmd(t, "frame .f"); tk->cmd(t, "label .f.l -text {Othello?} -background white"); tk->cmd(t, "button .f.c -text {Reset} -command {send cmd Reset}"); tk->cmd(t, "button .f.d -text {Quit} -command {send cmd Quit}"); tk->cmd(t, "pack .f.l .f.c .f.d -side left -fill x -expand 1"); tk->cmd(t, "pack .Wm_t .c .f -side top -fill x"); tk->cmd(t, "bind .c <ButtonRelease-1> {send cmd B1up %x %y}");
for (i := 1; i < 9; i++) for (j := 1; j < 9; j++) { coord := sys->sprint("%d %d %d %d", SQ*i, SQ*j, SQ*(i+1), SQ*(j+1)); tk->cmd(t, ".c create rectangle " + coord + " -outline black -width 2"); } tk->cmd(t, "update"); lasterror("init");
board = array[10] of {* => array[10] of int}; score = array[10] of {* => array[10] of int}; reinit();
for (;;) { alt { s := <- cmd => (n, l) := sys->tokenize(s, " \t"); case hd l { "Quit" => exit; "Reset" => reinit(); "B1up" => x := int hd tl l; y := int hd tl tl l; mouseUp(int x, int y); }
menu := <-menubut => wmlib->titlectl(t, menu); } } }
Note that now there are two channels watching events, one for the buttons and canvas within the Othello game itself, and one for the menubar. This time we need an alt statement to select from events on either channel. The value returned from the menubut channel indicates what the user did; everything is passed back to the titlectl function to be handled there.
If some call to the Tk module results in an error, an error string is made available in a pseudo-variable lasterror maintained by Tk. When this variable is read, it is reset. The function lasterror shows how to test and print this variable:
lasterror(where: string) { s := tk->cmd(t, "variable lasterror"); if (s != nil) sys->print("%s: tk error %s\n", where, s); }
I am very grateful to Steven Breitstein, Ken Clarkson, Sean Dorward, Eric Grosse, Doug McIlroy, Rob Pike, Jon Riecke, Dennis Ritchie, Howard Trickey, Phil Winterbottom, and Margaret Wright for explaining mysteries of Limbo and Inferno and for valuable suggestions on this paper.