aboutsummaryrefslogtreecommitdiffstats
path: root/src/com/craftinginterpreters/lox/Environment.java
diff options
context:
space:
mode:
authorGravatar Tom Willemse2020-11-25 23:10:58 -0800
committerGravatar Tom Willemse2020-11-25 23:10:58 -0800
commitca9fd3ae3a1ef5ca1fbe33a83abb12e656a2556f (patch)
tree77d16c7e6b87ed0f4472f6a421eeb9496d6f33bc /src/com/craftinginterpreters/lox/Environment.java
parent57e87978ef416ce2898a65a9b67e37be91263e67 (diff)
downloadcrafting-interpreters-ca9fd3ae3a1ef5ca1fbe33a83abb12e656a2556f.tar.gz
crafting-interpreters-ca9fd3ae3a1ef5ca1fbe33a83abb12e656a2556f.zip
Chapter 8: Add blocks and scopes
Diffstat (limited to 'src/com/craftinginterpreters/lox/Environment.java')
-rw-r--r--src/com/craftinginterpreters/lox/Environment.java17
1 files changed, 17 insertions, 0 deletions
diff --git a/src/com/craftinginterpreters/lox/Environment.java b/src/com/craftinginterpreters/lox/Environment.java
index 8d8a374..0a95282 100644
--- a/src/com/craftinginterpreters/lox/Environment.java
+++ b/src/com/craftinginterpreters/lox/Environment.java
@@ -4,13 +4,25 @@ import java.util.HashMap;
import java.util.Map;
class Environment {
+ private final Environment enclosing;
private final Map<String, Object> values = new HashMap<>();
+ Environment() {
+ enclosing = null;
+ }
+
+ Environment(Environment enclosing) {
+ this.enclosing = enclosing;
+ }
+
Object get(Token name) {
if (values.containsKey(name.lexeme)) {
return values.get(name.lexeme);
}
+ if (enclosing != null)
+ return enclosing.get(name);
+
throw new RuntimeError(name, "Undefined variable '" + name.lexeme + "'.");
}
@@ -20,6 +32,11 @@ class Environment {
return;
}
+ if (enclosing != null) {
+ enclosing.assign(name, value);
+ return;
+ }
+
throw new RuntimeError(name, "Undefined variable '" + name.lexeme + "'.");
}