Mutable lexical variables
Factor handbook » The language » Lexical variables

Prev:Lexical variables in literals
Next:Lexical variables and fry


When a lexical variable is bound using :>, ::, or [|, the variable may be made mutable by suffixing its name with an exclamation point (!).

A mutable lexical variable creates two new words in its scope. Assuming that we define a mutable variable with data :> var!, then:

var will push the value of the variable, data to the stack,

var! will consume a value from the stack, and set the variable to that value.

Note that using :> will always create a new local, and will not mutate the variable. Creating a new local with the same name may cause confusion, and have undesired effects.

The value of any variable can be modified by a word that modifies its arguments e.g. push. These words ignore mutable and immutable bindings.

Mutable bindings are implemented in a manner similar to that taken by the ML language. Each mutable binding is actually an immutable binding of a mutable cell. Reading the binding automatically unboxes the value from the cell, and writing to the binding stores into it.

Writing to mutable variables from outer lexical scopes is fully supported and has full closure semantics. See Examples of lexical variables for examples of mutable lexical variables in action.