You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

39 lines
764 B

require_relative "error"
module Lox
class Environment
def initialize(enclosing = nil)
@enclosing = enclosing
@values = {}
end
def define(name, value)
@values[name] = value
end
def get(token)
name = token.lexeme
if @values.has_key?(name)
@values[name]
elsif @enclosing
@enclosing.get(token)
else
raise RuntimeError.new(token, "Undefined variable '#{name}'.")
end
end
def assign(name, value)
lexeme = name.lexeme
if @values.has_key?(lexeme)
@values[lexeme] = value
elsif @enclosing
@enclosing.assign(name, value)
else
raise RuntimeError.new(name, "Undefined variable '#{lexeme}'.")
end
end
end
end