Value Assignments
A value assignment stores a value by a name on the stack. They can be placed in source files, building code, module functions or workbench functions.
The following example defines the variable a which from then is a reserved
name within the scope in which it was defined (locality).
In this case the source code file itself:
// source code file is the scope of a and b
use std::debug::*;
a = 5;
b = a * 2;
assert_eq([a, 5]);
assert_eq([b, 10]);
Locality
If you place a value assignment into a scope (using brackets {}), the defined
value is only available within that specific scope:
// source code file is the topmost scope #0
use std::debug::*;
// define a within scope #0
a = 5;
assert_eq([a, 5]);
// scope #1
{
// define b within scope #1
b = a * 2;
// of course b is available at this point
assert_valid("b");
// scope #2
{
// b is available in scope #2 because #2 is within #1
assert_valid("b");
}
}
// a is still available
assert_valid("a");
// b not known here anymore
assert_invalid("b");
Restrictions
No Shadowing
So-called "shadowing" (reusing a name) is prohibited. This restriction is highly intentional because µcad follows a concept of strict immutability1 of all value definitions.
So another assignment of a variable with the same name without an additional scope is prohibited.
a = 5;
a = a * 2; // error: a already defined in this scope
Even if using anonymous scopes this does not change.
a = 5;
{
a = a * 2;
std::debug::assert_eq([a, 10]);
}
[!NOTE] Anonymous scopes do not open new namespaces in µcad. This is different in a lot of other languages!
Not in modules
Value assignments are not available in modules:
mod my_module {
a = 1; // error
}
Not in initialization code
Value assignments are not available in workbenches' initialization code:
sketch MySketch() {
a = 1; // error
init(_x: Scalar) {}
}
MySketch();
-
Reusing names would undercut the ability to connect identifiers to values (labeling). ↩