Constant Assignments
Unlike values, constants are not stored on the stack but in the symbol table. For example this allows them to be accessed from within functions or workbenches in the same module where the constant is defined. Constants can be placed in source files, modules or initialization code.
const TEXT = "Hello";
mod my_module {
// constant assignment
const TEXT = "Hello my_module";
// public function
pub fn f() -> String {
TEXT
}
// public workbench
pub sketch MySketch(text: String) {
std::debug::assert_eq([TEXT, text]);
}
}
my_module::MySketch("Hello my_module");
std::debug::assert_eq([my_module::f(), "Hello my_module"]);
std::debug::assert_eq([TEXT, "Hello"]);
Additionally, constant assignments are permitted in the init code of a workbench, where value assignments are likewise prohibited.
sketch MySketch(text: String) {
// constant assignment in initialization code
const TEXT = "Hello";
init() {
text = TEXT;
}
std::print(text);
}
MySketch();
Restrictions
Uppercase naming
Constants are always written in UPPER_CASE.
const A = 1; // ok
const a = 1; // warning
const MyValue = 1; // warning
const MY_VALUE = 1; // ok
Ambiguous Names
A constant cannot be defined within the same module or workbench twice.
mod module {
const A = 5;
const A = 1; // error: ambiguous identifier in this module
pub mod another_module {
const A = 5; // ok
pub fn a() -> Integer { A }
}
pub sketch Sketch() {
const A = 5;
const A = 5; // error: ambiguous identifier in this workbench
}
}
std::debug::assert_eq([module::another_module::a(), 5]);
module::Sketch();
Not in building code
Constant assignments cannot be used in building code (the code below any initializers).
sketch MySketch() {
init(_: Integer) {}
const MY_CONST = 1; // error: not allowed in building code
}
MySketch();
Constant assignments must be on top of the workbench code if initializers are not used.
sketch MySketch() {
const MY_CONST = 1; // allowed if no initializers
}
MySketch();
They cannot be placed below non constant assignments within in a workbench.
sketch MySketch() {
_i = 5; // any non const code
const MY_CONST = 1; // error: const not allowed then
}
MySketch();
Not in function
Constant assignments cannot be used in functions.
fn f() {
const MY_CONST = 1; // error: not allowed in functions
}
f();
sketch MySketch() {
fn f() {
const MY_CONST = 1; // error: not allowed in workbench functions
}
f();
}
MySketch();
Not in initializers
Constant assignments cannot be used in initializers.
sketch MySketch() {
init(_: Integer) {
const MY_CONST = 1; // error: not allowed in initializers
}
}
MySketch();