Advertisement
babusha

Untitled

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