Locals and scope
CompilesA 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)Declaring
Section titled “Declaring”let count: int = 0 // with a typelet label = "ready" // type taken from the valueA 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.
Changing
Section titled “Changing”Use let mut for a local you intend to change, then assign with =:
let mut attempts: int = 0attempts = attempts + 1There 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.
Locals versus fields
Section titled “Locals versus fields”| 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.