lib/interpreter/interpreter.rb in nudge-0.1.0 vs lib/interpreter/interpreter.rb in nudge-0.1.1

- old
+ new

@@ -14,18 +14,20 @@ class Interpreter attr_accessor :program, :stepLimit, :steps attr_accessor :stacks, :instructions_library, :variables, :names, :types attr_accessor :last_name, :evaluate_references + attr_accessor :sensors # A program to be interpreted can be passed in as an optional parameter def initialize(params = {}) initialProgram = params[:program] || nil @program = initialProgram @types = params[:types] || NudgeType.all_types @stepLimit = params[:step_limit] || 3000 + @sensors = Hash.new instructions = params[:instructions] || Instruction.all_instructions @instructions_library = Hash.new {|hash, key| raise InstructionPoint::InstructionNotFoundError, "#{key} is not an active instruction in this context"} instructions.each {|i| self.enable(i)} @@ -52,10 +54,11 @@ # * resets the @step counter. def reset(program=nil) @program = program self.clear_stacks self.reset_names + self.reset_sensors if program @stacks[:exec].push(NudgeProgram.new(program).linked_code) end @steps = 0 @evaluate_references = true @@ -65,10 +68,15 @@ def clear_stacks @stacks = Hash.new {|hash, key| hash[key] = Stack.new(key) } end + def depth(stackname) + @stacks[stackname].depth + end + + def peek(stackname) @stacks[stackname].peek end @@ -125,10 +133,11 @@ # invoke self.step() until a termination condition is true def run while notDone? self.step end + fire_all_sensors end def lookup(name) @variables[name] || @names[name] @@ -223,8 +232,27 @@ end def disable_all_types @types = [] + end + + + def register_sensor(name, &block) + raise(ArgumentError, "Sensor name #{name} is not a string") unless name.kind_of?(String) + @sensors[name] = block + end + + + def reset_sensors + @sensors = Hash.new + end + + + def fire_all_sensors + @sensors.inject({}) do |result, (key, value)| + result[key] = @sensors[key].call(self) + result + end end end end \ No newline at end of file