Class: AmberVM::Interpreter::Loop

Inherits:
Element show all
Defined in:
lib/amber/interpreter.rb

Overview

This is a loop. It is executed over and over again as long as the passed condition evaluates to a value that matches is_true?.


TODO: Add BreakException to stop execution of loops. TODO: Add NextExceeption to skip rest of a evaluation on loop code.

Instance Attribute Summary

Attributes inherited from Element

#pos

Instance Method Summary collapse

Constructor Details

#initialize(condition, body, pos = nil) ⇒ Loop

Initializes a new loop.

condition

is executed before each run of the loop. If it evaluates to true the loop is executed another time otherwise the exection ends.

body

For each itteration of the loop this is executed once.

pos

The position within the source code of the definition - for deugging purpose.



369
370
371
372
373
# File 'lib/amber/interpreter.rb', line 369

def initialize(condition, body, pos = nil)
  super(pos)
  @condition = condition
  @body = body
end

Instance Method Details

#execute(env) ⇒ Object

The loop will execute as long as the code passed as condition evaluates to is_true?. Once the loop stops executing the return value is the result of the last body execution.



387
388
389
390
391
392
393
# File 'lib/amber/interpreter.rb', line 387

def execute env
  r = nil
  while @condition.execute(env).is_true?
    r = @body.execute(env)
  end
  r
end

#optimize(variables = {}) ⇒ Object

Optimization of the loop



396
397
398
399
400
# File 'lib/amber/interpreter.rb', line 396

def optimize variables = {}
  condition = @condition.optimize variables
  body = @body.optimize variables
  Loop.new(condition, body, @pos)
end

#pretty_print(q) ⇒ Object



375
376
377
378
379
380
381
# File 'lib/amber/interpreter.rb', line 375

def pretty_print(q)
  first = true
  q.text "while ("
  q.pp @condition
  q.text ")"
  q.pp @body
end