Matchbox 0.2

Variables

Variables give names to values. Declare a variable by specifying its name and type:

var number int

A variable declaration tells the compiler that a variable exists, including its name and type. The type is required because it tells Matchbox how much memory to reserve for the variable. A variable definition is a declaration that also gives the variable an initial value. Every definition is inherently a declaration, but not every declaration is a definition.

Matchbox is statically typed, so a variable's type is known when the program is compiled. That lets the compiler check assignments before the program runs and gives generated bytecode a predictable value shape to work with.

Assign a value before using the variable:

number = 10

Initialization

A variable can receive its first value as part of the statement. When it does, the statement is a variable definition:

var width = 10
var height = 20
var area = width * height

Matchbox infers int from these initial values at compile time. An explicit type can also be included:

var answer int = 42

Matchbox 0.2 only provides the int type. When a declaration has an initializer, the initializer determines the type.

An initializer gives a declared variable its first value. If a declaration does not include an initial value, the variable must be assigned before it is read.

Using Declared Variables

A variable declared without an initializer cannot be read until a later assignment gives it a value:

var count int
count = 1
print(count)

Reading it before count = 1 produces an is uninitialized diagnostic. Assigning to an undeclared name produces an is undefined diagnostic.

Redeclaration and Shadowing

A name cannot be declared twice in the same scope. A function-local variable may use the same name as a top-level variable; the local declaration then shadows the top-level name inside that function:

var value = 10

func show() int {
    var value = 20
    return value
}

All values in 0.2 are integers, so assignments must also produce an integer.

Naming

Use names that describe the value's role. Names such as total, count, and maximum are easier to follow than single-letter names outside small expressions.

Names can contain ASCII letters, digits, and underscores, but cannot begin with a digit. Reserved words cannot be used as names.

Next Step

Continue to Expressions, or see Types for the int reference.