Closures & Lexical Scoping
Understand how enclosed environments and lexical variable capture work in NouvaLang runtime.
1. Lexical Block Scoping
Variables declared inside a block (such as inside an if statement, loop, or function) are scoped exclusively to that block and its child environments:
let global_message: str = "Outer";
if true {
let inner_message: str = "Inner";
print(global_message); // Accessible: "Outer"
print(inner_message); // Accessible: "Inner"
}
// Accessing inner_message here will result in an Undefined variable error
2. Environment Enclosure & First-Class Functions
When a function is created, it retains a reference to its enclosing lexical environment:
let base_multiplier: int = 10;
fun scale(factor: int) -> int {
return factor * base_multiplier; // Captures base_multiplier
}
print(scale(5)); // 50