Namespaces and files
NAMESPACE
A namespace is a named place to keep things, so that two parts of a program
can each have a start without colliding.
NAMESPACE Audio
volume = 7
FUNCTION louder()
volume = volume + 1
RETURN volume
END FUNCTION
END NAMESPACE
NAMESPACE Video
FUNCTION louder()
RETURN "that's not my job"
END FUNCTION
END NAMESPACE
PRINT Audio.louder(), Audio.volume
PRINT Video.louder()
8 8
that's not my job
From outside you reach in with a dot. From inside, the namespace’s own things need no prefix. Types and constants live in them too — a namespace of constants makes a tidy set of named numbers.
NAMESPACE Mode
CONST idle = 0
CONST playing = 1
CONST paused = 2
END NAMESPACE
now = Mode.playing
IF now = Mode.playing THEN PRINT "the game is on"
the game is on
ENUM
A namespace of constants that just count upward is so common that there’s a
shorter way to write it. An ENUM numbers its members for you: the first is
0, and each one after is one more than the one before.
ENUM Mode
idle
playing
paused
END ENUM
PRINT Mode.idle, Mode.playing, Mode.paused
now = Mode.paused
IF now = Mode.paused THEN PRINT "press any key"
0 1 2
press any key
Give a member a value and the counting carries on from there. You can put several on a line, and a value can use the members before it — handy for flags that get combined.
ENUM Tile
grass, sand, water // 0, 1, 2
wall = 100, door, window // 100, 101, 102
END ENUM
ENUM Flag
solid = 1, sticky = 2, deadly = 4
lava = sticky | deadly
END ENUM
PRINT Tile.water, Tile.door, Tile.window
PRINT Flag.lava, Flag.lava & Flag.deadly
2 101 102
6 4
An ENUM is a namespace underneath, so everything you know about those
applies: its members can’t be changed, and it can live inside another
namespace.
From BASIC:
BEGIN ENUMisENUM, and the members are reached through its name:Mode.idle.
From Python: An
Enumwhose members are plain numbers.Mode.idleis just0.
From JavaScript: The frozen object of numbers you’ve written by hand a hundred times.
From Lua: The table of named numbers, without the table.
From Python and Lua: A namespace is like a module, but you can have several in one file, or one spread over several files.
From JavaScript: Think of an object that only holds declarations, checked before the program runs.
IMPORT
IMPORT brings in another file. This tutorial keeps one called shapes for
you to try it on. It holds a namespace, Shapes, with area, edge and a
constant, sides.
IMPORT "shapes"
PRINT Shapes.area(3, 4)
PRINT Shapes.edge(3, 4)
PRINT "a rectangle has", Shapes.sides, "sides"
12
14
a rectangle has 4 sides
The name is the file’s path without its .crash. Everything a file declares
at its top level is yours once you’ve imported it, and a file imported twice
is only read once.
Crash-tan’s Tip: Put a library’s things in a namespace named after it. Then whoever imports it can see at a glance where
Shapes.areacame from.