Skip to content

Locals and scope

Compiles

A locallocal: A variable declared with let inside a function. It exists only until the function returns. is a variable declared with let inside a function. It holds a value while the function runs and disappears when the function returns. Locals are how you give a name to an intermediate result:

let me: Entity = $entity.get()
let name: string = $entity.get_name(me)
$debug.print_line("I am {}", [name], false)
let count: int = 0 // with a type
let label = "ready" // type taken from the value

A local must be given a value when it is declared. If there’s nothing sensible yet, use null for a handle, 0 for a number, "" for text.

Use let mut for a local you intend to change, then assign with =:

let mut attempts: int = 0
attempts = attempts + 1

There is no += or ++: write x = x + 1.

A local can be used from the line it’s declared on to the end of the block { … } it’s declared in:

fn describe(score: int) -> string {
let mut label: string = "low"
if score > 10 {
let bonus: int = score - 10 // only exists inside this if
label = "high"
}
return label // `bonus` can't be used here
}

The same name can’t be declared twice in one block. An inner block may declare a name the outer block already has; inside the inner block, the name means the inner one.

Local Field
Declared Inside a function At the top of the script
Lives Until the function returns As long as the component
Use it for Working out an answer Settings and remembered state

If you find yourself wishing a local still had its value next frame, it should be a let mut field.

For programmers

The compiler does not currently enforce mut on locals; reassigning a plain let compiles. Write mut anyway; it documents intent and a future compiler may check it. Locals are stack slots; there are no closures, so nothing captures a local beyond its function.