Advertisement
babusha

Untitled

Jul 20th, 2011
1,794
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.02 KB | None | 0 0
  1. require 'rubygems'
  2. require 'bindata'
  3. require 'readline'
  4.  
  5. class VirtualMachine
  6.     def self.debug=(debug = false)
  7.         @@debug = debug
  8.     end
  9.    
  10.     def self.run bytecode
  11.         cells = Array.new
  12.         @plus     = 0x1
  13.         @minus    = 0x2
  14.         @next     = 0x3
  15.         @previous = 0x4
  16.         @read     = 0x5
  17.         @print    = 0x6
  18.         cell  = 0
  19.         ip    = 0
  20.         while not bytecode.size == ip
  21.             if cells[cell].nil?
  22.                 cells[cell] = 0
  23.             end
  24.            
  25.             case bytecode[ip]
  26.             when @plus
  27.                 cells[cell] += 1
  28.             when @minus
  29.                 cells[cell] -= 1
  30.             when @next
  31.                 cell += 1
  32.             when @previous
  33.                 cell -= 1
  34.             when @read
  35.                 cells[cell] = Readline.readline('',true).chomp.to_i
  36.             when @print
  37.                 print cells[cell].chr
  38.             end    
  39.             ip += 1
  40.         end
  41.     end
  42. end
  43.  
  44. VirtualMachine.debug = true
  45. ARGV.each do |file_name|
  46.     if not File.exist? file_name
  47.         puts "File #{file_name} doesn't exist!"
  48.         exit 1
  49.     end
  50.     bytecode = Array.new
  51.     File.open(file_name) do |file|
  52.         file.each_byte do |ch|
  53.             bytecode[bytecode.size] = ch
  54.         end
  55.     end
  56.     VirtualMachine.run bytecode
  57. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement