diff options
Diffstat (limited to 'src/com/craftinginterpreters/lox/Environment.java')
-rw-r--r-- | src/com/craftinginterpreters/lox/Environment.java | 17 |
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 + "'."); } |