Reading — step 1 of 3
Variables — Naming Values
Variable Declaration & Assignment
Variables give names to values, allowing programs to store and manipulate state. This is where our language starts feeling like a real programming language.
Declaration
The var keyword declares a new variable:
var x = 10; // declare x with initial value 10
var name = "Lox"; // declare name with initial value "Lox"
var y; // declare y with no initializer (defaults to nil)
Assignment
The = operator reassigns an existing variable:
var x = 10;
x = 20; // x is now 20
print x; // outputs: 20
Assignment is an expression in our language, meaning it produces a value: x = 20 evaluates to 20. This enables chaining: a = b = 5; sets both a and b to 5, because b = 5 evaluates to 5, which is then assigned to a.
The Environment
Variables are stored in an environment — a mapping from names to values:
Environment {
values: Map<String, Value>
}
When we evaluate a variable expression like x, we look it up in the environment. When we execute a var declaration, we add a new entry. When we execute an assignment, we update an existing entry.
Error Cases
Two important errors:
- Undefined variable: using a variable that has not been declared →
Undefined variable 'z'. - Already declared: some languages allow re-declaration (JavaScript with
var), others do not (Rust withlet). We will allow it at the top level (like Python) but not within the same scope.
How Languages Handle Variables
Python does not have a var keyword — assignment creates variables implicitly. This makes typos dangerous (naem = "Bob" silently creates a new variable). JavaScript has three keywords (var, let, const) with different scoping rules, which is widely considered a design mistake. Lua uses local for local variables and implicitly creates globals — another source of bugs. Our var keyword is explicit and straightforward.
Your Task
Implement var declarations, variable expressions, and assignment. Store variables in an environment map and report errors for undefined variables.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…