From 78f3d0ee766674f4e9078f347fbb20588c19bcd9 Mon Sep 17 00:00:00 2001 From: Alpha Chen Date: Wed, 17 Aug 2022 21:06:26 -0700 Subject: [PATCH] 10.4.2 --- ruby/lib/lox/environment.rb | 4 ++++ ruby/lib/lox/interpreter.rb | 9 ++++++++- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/ruby/lib/lox/environment.rb b/ruby/lib/lox/environment.rb index 543e07e..f962e90 100644 --- a/ruby/lib/lox/environment.rb +++ b/ruby/lib/lox/environment.rb @@ -46,5 +46,9 @@ module Lox raise RuntimeError.new(name, "Undefined variable '#{lexeme}'.") end end + + def assign_at(distance, name, value) + ancestor(distance).values[name] = value + end end end diff --git a/ruby/lib/lox/interpreter.rb b/ruby/lib/lox/interpreter.rb index d194c00..c36e7cb 100644 --- a/ruby/lib/lox/interpreter.rb +++ b/ruby/lib/lox/interpreter.rb @@ -135,7 +135,14 @@ module Lox def visit_assign(expr) value = evaluate(expr.value) - @env.assign(expr.name, value) + + if @locals.has_key?(expr) + distance = @locals.get(expr) + @env.assign_at(distance, expr.name, value) + else + @globals.assign(expr.name, value) + end + value end