From ca9fd3ae3a1ef5ca1fbe33a83abb12e656a2556f Mon Sep 17 00:00:00 2001 From: Tom Willemse Date: Wed, 25 Nov 2020 23:10:58 -0800 Subject: Chapter 8: Add blocks and scopes --- src/com/craftinginterpreters/lox/Environment.java | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) (limited to 'src/com/craftinginterpreters/lox/Environment.java') 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 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 + "'."); } -- cgit v1.2.3-54-g00ecf