Skip to main content

Static variables

A variable is a named location in memory that stores a value. Static variables are variables that can be accessed from any function. They are declared at the top level of a file, outside all function declarations.

let NumBananas = 0
const DesiredBananas = 5

fn AddBanana() {
NumBananas += 1
}

fn RemoveBanana() {
NumBananas -= 1
}

fn HasEnoughBananas() -> boolean {
return NumBananas >= DesiredBananas
}

Static context variables can also be declared with use. They will automatically be provided to implicitly to any function in the same file that requires a context parameter. See Context for more information.

use color=#8800ff
pub fn Example() {
FunctionThatRequiresContext // color will be provided implicitly from context
}
pub fn FunctionThatRequiresContext([color]) { }

Declaration

A static variable must be declared with let, const or use.

  • let declares a mutable static variable, which can be reassigned.
  • const declares an immutable static variable, which cannot be reassigned.
  • use declares a static context value, which is provided implicitly to any function in the same file that requires a context parameter.

An initializer expression, specified after an equals (=) sign, is optional for static variables declared with let, but mandatory for const and use static variables as these cannot be changed and so must be set when they are declared.

let numBananas
const DesiredBananas = 5
use color=#8800ff

Static variables can be declared as public using the pub keyword, which allows them to be accessed from all files in the program. Otherwise, they are private and can only be accessed from within the same file. Static context values declared with use cannot be made public.

The variable's name must begin with an uppercase letter if it is public, otherwise any casing is acceptable.

pub let NumBananas
pub const DesiredBananas = 5

Working with static variables

Read a static variable using its name.

let value = NumBananas

Write to a static variable by using an assignment statement =. This is only supported for static variables declared with let.

NumBananas = 100