Constants
A constant is a top-level name that every function can read and nothing can
reassign. It is declared with const, a type, a name, and a value:
const int MAX_DEPTH = 200
const str UNIT = "points"
const str[] GRADES = ["low", "fair", "good"]
func grade(int score) str do
return GRADES[score * len(GRADES) / (MAX_DEPTH + 1)]
endConstants are set before any other code runs, in an order that puts each after the constants it uses, so they may be declared in any order, in any file, and used anywhere. A constant's value may call functions: the constants those functions read, and those read by the functions they call, are set first.
const int[] SQUARES = squares(LIMIT)
const int LIMIT = 4
func squares(int n) int[] do
int[] out = []
for i = 1 to n do
push(out, i * i)
end
return out
endA constant that needs its own value is an error, and when it reaches itself
through functions the error names the way it does:
Constant 'A' depends on itself: A uses f uses g uses B uses A.
Assigning to a constant is an error, and no variable or parameter may take a
constant's name. A constant's arrays and maps, with those inside them, cannot
change either: push(GRADES, "great") is a compile error, and a change made
through another name for the same array, such as a parameter, stops the
program with a runtime error. The fields of a constant's struct can change.
Variables of a module
shared before a declaration at the top level of a file makes a variable
of the whole module: like a constant, every function can read it and its
value is set before other code runs, but it can be assigned and its arrays
and maps can change. It holds state that a module's functions share:
shared int calls = 0
shared str[] history = []
func record(str event) do
calls += 1
push(history, event)
endpub shared lets other modules use it too. Inside a function no word is
needed: a variable is shared with the functions written there
that change it.
Variables that cannot change
let declares a variable that cannot be assigned after its declaration:
let int limit = 10. As for a constant, the array or struct it refers to
can still change.