ZetCode

Modula-2 local modules

last modified November 27, 2026 Modula-2

A module does not have to live in a file of its own. A local module is declared inside a program module, or inside a procedure, and hides its variables from the code around it just as a library module does. It has an export list, an import list and a body, but no definition module and no separate compilation. Local modules give a single-file program the information hiding of the modules article.

A local module

A local module is declared among the declarations of the program with MODULE, a name, and a semicolon, and ends with END and the name followed by a semicolon. Its EXPORT list names what the surrounding program may use.

numbering.mod
MODULE numbering;
FROM InOut IMPORT WriteString, WriteCard, WriteLn;

MODULE Counter;
  EXPORT Next;

  VAR
    n: CARDINAL;

  PROCEDURE Next(): CARDINAL;
  BEGIN
    INC(n);
    RETURN n
  END Next;

BEGIN
  n := 0
END Counter;

BEGIN
  WriteString("first: "); WriteCard(Next(), 0); WriteLn;
  WriteString("second: "); WriteCard(Next(), 0); WriteLn;
  WriteString("third: "); WriteCard(Next(), 0); WriteLn
END numbering.

Counter exports the procedure Next and keeps the variable n to itself. Unlike a local variable of a procedure, n lives as long as the program, so each call of Next continues where the previous one stopped. The body of Counter sets n to zero before the program body starts. The program uses Next without a module prefix: the export list makes the name visible in the surrounding scope.

$ gm2 numbering.mod -o numbering
$ ./numbering
first: 1
second: 2
third: 3

A closed scope

A procedure sees the names of the module around it. A local module does not: its scope is closed, and names from outside must be imported. The next program forgets the import.

closed.mod
MODULE closed;
FROM InOut IMPORT WriteCard, WriteLn;

CONST
  Limit = 5;

VAR
  total: CARDINAL;

MODULE Adder;
  EXPORT Add;

  PROCEDURE Add(x: CARDINAL);
  BEGIN
    IF x <= Limit THEN INC(total, x) END
  END Add;

END Adder;

BEGIN
  total := 0;
  Add(3);
  WriteCard(total, 0); WriteLn
END closed.

Add uses the constant Limit and the variable total of the program, but neither is visible inside Adder. Standard identifiers such as INC and CARDINAL are always visible and need no import.

$ gm2 closed.mod -o closed
closed.mod:15:13: error: In procedure ‘Add’: ‘Limit’ has not been declared
   15 |     IF x <= Limit THEN INC(total, x) END
      |             ^~~~~
closed.mod:15:24: error: base procedure INC expects a variable as a parameter but was given an unknown
   15 |     IF x <= Limit THEN INC(total, x) END
      |                        ^~~
closed.mod:15:28: error: In inner module ‘Adder’: unknown symbol ‘total’
   15 |     IF x <= Limit THEN INC(total, x) END
      |                            ^~~~~
closed.mod:18:10: error: the following unknown symbols in module ‘Adder’ were unresolved: total
   18 | END Adder;
      |          ^

Importing names

IMPORT in a local module brings names of the surrounding scope inside. FROM … IMPORT takes names from a library module, as in a program module.

adder.mod
MODULE adder;
FROM InOut IMPORT WriteString, WriteCard, WriteLn;

CONST
  Limit = 5;

VAR
  total: CARDINAL;

MODULE Adder;
  FROM InOut IMPORT WriteString, WriteCard, WriteLn;
  IMPORT Limit, total;
  EXPORT Add;

  PROCEDURE Add(x: CARDINAL);
  BEGIN
    IF x <= Limit THEN
      INC(total, x)
    ELSE
      WriteString("skipping "); WriteCard(x, 0); WriteLn
    END
  END Add;

END Adder;

BEGIN
  total := 0;
  Add(3);
  Add(9);
  Add(4);
  WriteString("total: "); WriteCard(total, 0); WriteLn
END adder.

IMPORT Limit, total makes the program's constant and variable visible in Adder, and Add changes the program's total directly. Adder imports the output procedures from InOut on its own; the import of the program module does not reach inside. The two lists document exactly what the local module depends on.

$ gm2 adder.mod -o adder
$ ./adder
skipping 9
total: 7

Hidden names

The closed scope works in the other direction too. A name declared in a local module and not exported cannot be used outside it.

hidden.mod
MODULE hidden;
FROM InOut IMPORT WriteCard, WriteLn;

MODULE Counter;
  EXPORT Next;

  VAR
    n: CARDINAL;

  PROCEDURE Next(): CARDINAL;
  BEGIN
    INC(n);
    RETURN n
  END Next;

BEGIN
  n := 0
END Counter;

BEGIN
  n := 100;
  WriteCard(Next(), 0); WriteLn
END hidden.

The program tries to set the counter of Counter directly. n is not in the export list, so the program does not know the name. Only Next can change it.

$ gm2 hidden.mod -o hidden
hidden.mod:21:3: error: In program module ‘hidden’: unknown symbol ‘n’
   21 |   n := 100;
      |   ^
hidden.mod:23:11: error: the following unknown symbols in module ‘hidden’ were unresolved: n
   23 | END hidden.
      |           ^

Module bodies

The bodies of local modules run before the body of the program, in the order in which the modules are declared. A module may export a variable as well as a procedure.

startup.mod
MODULE startup;
FROM InOut IMPORT WriteString, WriteLn;

MODULE Config;
  FROM InOut IMPORT WriteString, WriteLn;
  EXPORT verbose;

  VAR
    verbose: BOOLEAN;

BEGIN
  verbose := TRUE;
  WriteString("Config body"); WriteLn
END Config;

MODULE Report;
  FROM InOut IMPORT WriteString, WriteLn;
  IMPORT verbose;
  EXPORT Say;

  PROCEDURE Say(msg: ARRAY OF CHAR);
  BEGIN
    IF verbose THEN WriteString(msg); WriteLn END
  END Say;

BEGIN
  Say("Report body")
END Report;

BEGIN
  Say("program body");
  verbose := FALSE;
  Say("not printed")
END startup.

Config exports the variable verbose and sets it in its body. Report imports verbose and uses it in its own body, which works because Config is declared, and therefore initialised, first. The program body then turns verbose off, and the last message is not printed. An exported variable can be changed by anyone who sees it, which is why most modules export procedures instead.

$ gm2 startup.mod -o startup
$ ./startup
Config body
Report body
program body

Exported names must be unique

Exported names join the scope around the module, so two local modules in one scope cannot export the same name.

twice.mod
MODULE twice;

MODULE Celsius;
  EXPORT Reset;

  PROCEDURE Reset;
  BEGIN
  END Reset;

END Celsius;

MODULE Fahrenheit;
  EXPORT Reset;

  PROCEDURE Reset;
  BEGIN
  END Reset;

END Fahrenheit;

BEGIN
  Reset
END twice.

Both Celsius and Fahrenheit export Reset, and the second declaration clashes with the first. Wirth's book allows EXPORT QUALIFIED in a local module, so the names would be written Celsius.Reset and Fahrenheit.Reset, but gm2 rejects it with "QUALIFIED not allowed in an inner module". The exported names of local modules therefore need distinct names, such as ResetCelsius.

$ gm2 twice.mod -o twice
twice.mod:6:13: error: In procedure ‘Reset’: first proper declaration of procedure ‘Reset’
    6 |   PROCEDURE Reset;
      |             ^~~~~
twice.mod:15:13: error: procedure ‘Reset’ has already been declared
   15 |   PROCEDURE Reset;
      |             ^~~~~

Local modules in procedures

A local module may also be declared inside a procedure. It then lives only while the procedure runs, and its body runs on every call.

inproc.mod
MODULE inproc;
FROM InOut IMPORT WriteString, WriteCard, WriteLn;

PROCEDURE Run(times: CARDINAL);
VAR
  i: CARDINAL;

  MODULE Tally;
    FROM InOut IMPORT WriteString, WriteLn;
    EXPORT Count, count;

    VAR
      count: CARDINAL;

    PROCEDURE Count;
    BEGIN
      INC(count)
    END Count;

  BEGIN
    count := 0;
    WriteString("  Tally starts"); WriteLn
  END Tally;

BEGIN
  FOR i := 1 TO times DO
    Count
  END;
  WriteString("  counted "); WriteCard(count, 0); WriteLn
END Run;

BEGIN
  WriteString("Run(3)"); WriteLn;
  Run(3);
  WriteString("Run(5)"); WriteLn;
  Run(5)
END inproc.

Tally is declared among the local declarations of Run and exports a procedure and a variable to it. Each call of Run creates the module anew: the body prints its message and sets count to zero again, so the second call counts 5, not 8.

$ gm2 inproc.mod -o inproc
$ ./inproc
Run(3)
  Tally starts
  counted 3
Run(5)
  Tally starts
  counted 5

A random number generator

A random number generator keeps a state between calls that no other part of the program should touch, which makes it a natural local module. This one is a linear congruential generator with a 16-bit state.

dice.mod
MODULE dice;
FROM InOut IMPORT WriteString, WriteCard, WriteLn;

MODULE Random;
  EXPORT Seed, Below;

  VAR
    state: CARDINAL;

  PROCEDURE Seed(s: CARDINAL);
  BEGIN
    state := s MOD 65536
  END Seed;

  PROCEDURE Below(limit: CARDINAL): CARDINAL;
  BEGIN
    state := (state * 25173 + 13849) MOD 65536;
    RETURN state * limit DIV 65536
  END Below;

BEGIN
  state := 1
END Random;

VAR
  i, roll: CARDINAL;
  counts: ARRAY [1..6] OF CARDINAL;

BEGIN
  Seed(2026);
  FOR i := 1 TO 6 DO counts[i] := 0 END;
  FOR i := 1 TO 600 DO
    roll := Below(6) + 1;
    INC(counts[roll])
  END;
  FOR i := 1 TO 6 DO
    WriteCard(i, 0); WriteString(": "); WriteCard(counts[i], 3); WriteLn
  END
END dice.

Seed sets the state, and Below(limit) computes the next state and scales it to a number from 0 to limit - 1. The products stay below 232, so the CARDINAL arithmetic never overflows. The program rolls a die 600 times and counts each face; the same seed gives the same counts on every run. Generators of this size are fine for games and tests, not for statistics; GNU Modula-2 ships a better one, shown in the random numbers article.

$ gm2 dice.mod -o dice
$ ./dice
1:  90
2:  92
3: 116
4: 114
5: 100
6:  88

A moving average

The last program uses two local modules. Random simulates the load of a server once an hour, and Window keeps the last four readings and their mean.

average.mod
MODULE average;
FROM InOut IMPORT WriteString, WriteCard, WriteLn;

MODULE Random;
  EXPORT Below;

  VAR
    state: CARDINAL;

  PROCEDURE Below(limit: CARDINAL): CARDINAL;
  BEGIN
    state := (state * 25173 + 13849) MOD 65536;
    RETURN state * limit DIV 65536
  END Below;

BEGIN
  state := 2026
END Random;

MODULE Window;
  EXPORT Add, Mean;

  CONST
    Size = 4;

  VAR
    values: ARRAY [0..Size - 1] OF CARDINAL;
    next, count, sum: CARDINAL;

  PROCEDURE Add(x: CARDINAL);
  BEGIN
    IF count = Size THEN
      DEC(sum, values[next])
    ELSE
      INC(count)
    END;
    values[next] := x;
    INC(sum, x);
    next := (next + 1) MOD Size
  END Add;

  PROCEDURE Mean(): CARDINAL;
  BEGIN
    RETURN sum DIV count
  END Mean;

BEGIN
  next := 0; count := 0; sum := 0
END Window;

VAR
  hour, reading: CARDINAL;

BEGIN
  FOR hour := 1 TO 10 DO
    reading := 40 + Below(30);
    Add(reading);
    WriteString("hour "); WriteCard(hour, 2);
    WriteString(": load "); WriteCard(reading, 2);
    IF hour >= 4 THEN
      WriteString(", mean of last 4: "); WriteCard(Mean(), 2)
    END;
    WriteLn
  END
END average.

Window stores the readings in a ring buffer: next is the slot for the next value, and once the buffer is full each new value replaces the oldest one, whose amount is taken off the running sum. The mean is therefore computed without a loop, and the program prints it once four readings are in. The program body sees only Below, Add and Mean; the array, the counters and the generator's state stay inside their modules.

$ gm2 average.mod -o average
$ ./average
hour  1: load 52
hour  2: load 51
hour  3: load 57
hour  4: load 53, mean of last 4: 53
hour  5: load 62, mean of last 4: 55
hour  6: load 60, mean of last 4: 58
hour  7: load 47, mean of last 4: 55
hour  8: load 52, mean of last 4: 55
hour  9: load 53, mean of last 4: 53
hour 10: load 52, mean of last 4: 51

Source

The GNU Modula-2 manual

Modula-2 language reference at modula2.org

In this article we have declared local modules in a program and in a procedure, exported procedures and variables, imported names from the surrounding scope and from library modules, hidden variables, followed the order of module bodies, and written a random number generator and a moving average. A local module that grows useful in several programs becomes a library module, as described in the modules article; the opaque types article hides a type as well as variables.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Modula-2 tutorials.