Files
rlox/rlox/environment.rb
2018-07-25 15:32:37 +02:00

47 lines
971 B
Ruby
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

require './rlox/call'
class Environment
def self.global()
env = self.new()
env.define("print", Callable.new("print", 1) { | args | puts args[0] })
env.define("clock", Callable.new("clock", 0) { | args | Time.now.to_i })
env
end
def initialize(parent=nil)
@values = {}
@parent = parent
end
def to_s()
@values.to_s
end
def define(name, value)
@values[name] = value
end
def get(name)
if @values.has_key? name.lexeme
return @values[name.lexeme]
end
if @parent != nil
return @parent.get(name)
end
raise ExecError.new(name.line, "Undefined variable '#{name.lexeme}'.")
end
def assign(name, value)
if @values.has_key? name.lexeme
@values[name.lexeme] = value
return
end
if @parent != nil
return @parent.assign(name, value)
end
raise ExecError.new(name.line,
"Cant assign undefined variable '#{name.lexeme}'.")
end
end