Variables and Bindings
Declarations bind names to values. There are three binding declarations: const, val, and var.
const MaxRetries = 3;
val limit = MaxRetries * 2;
var attempts = 0;
attempts = attempts + 1;
print(MaxRetries, limit, attempts);3 6 1constdeclares a compile-time constant: the value must be computable at compile time and cannot be reassigned afterwards. Use it for the limits, thresholds, and configuration numbers baked into the program;valdeclares an immutable binding:limitis 6 from now on and cannot change;vardeclares a mutable variable:attemptswent from 0 to 1.
Like val, const refuses reassignment:
MaxRetries = 4; // ✗ a const name cannot be reassignedvar has one more trick its two siblings lack: declare first, assign later (the type must be written out):
var counter: int;
counter = 0;
counter += 10;
print(counter);10Use val whenever you can; promote constants that are genuinely set in stone to const; leave var for values that really do change.
Compile-time evaluation of const
A const initial value is evaluated and folded at compile time: literal arithmetic (6 * 7), references to other consts, and whitelisted Math functions from the standard library may all appear in a const position, and the result is baked straight into the compiled output:
const ConstFolded: int = Math.Clamp(80 * 2, 0, 100);
print(ConstFolded);100What may appear in a const position has clear bounds; for more elaborate compile-time computation, use a const func (see const funcs).
Destructuring declarations
val / var also support a destructuring form: a pattern on the left declares several names at once. Vectors and tuples can both be unpacked:
val (x, y) = vec2i(3, 4);
print(x, y);3 4Destructuring is just declaration-position syntax; the patterns themselves belong to the pattern system, whose full set is covered on the patterns page.
Notes
- Names for all three bindings follow the identifier rules and are case-sensitive.
- A
constinitial value is evaluated at compile time and limited to what that position allows; see const funcs for details. - Binding types are usually inferred; when inference fails, write the type after the colon (like
counter: intabove).
