Skip to content

Latest commit

 

History

History
46 lines (31 loc) · 1.08 KB

File metadata and controls

46 lines (31 loc) · 1.08 KB
title Variables

Variables are named slots for storing values. You define a new variable in Ghost using the := operator, like so:

a := 1 + 2

This creates a new variable a in the current scope and initializes it with the result of the expression following :=. Once a variable has been defined, it can be accessed by name as you would expect.

technology := "Micromachines"

print(technology) // >> Micromachines

Scope

Ghost has true block scope: a variable exists from the point where it is defined until the end of the block where that definition appears.

function foobar() {
    print(a)  // Error: "a" doesn't exist yet.

    a := 123

    print(a) // >> 123
}

print(a)  // Error: "a" doesn't exist anymore.

Variables defined at the top level of a script are top-level, or global. All other variables are local. Declaring a variable in an inner scope with the same name as an outer one is called shadowing and is not an error.

a := "outer"

function foobar() {
    a := "inner"

    print(a)  // inner
}

print(a)  // outer