Wednesday, April 18, 2012

BF Interpreter; Updates

I've been working on projects recently, so I should have some interesting things to put on here again.  This is a pretty simple thing, but I wrote a BF interpreter in ruby.  BF is a very simple language, so the interpreter is short and doesn't need any sophisticated parsing (all bf instructions are one character).

Code can be found after the break.

MAX = 255
size = 100
if ARGV[1] != NIL
  size = ARGV[1].to_i
end
#read the file and stuff
if ARGV[0] == nil
  puts "Needs a file"
  return
end
file = File.new(ARGV[0])
input = file.readlines.join

cells = Array.new(size).fill(0)
inst = 0
data = 0

while inst < input.length
  char = input[inst].chr
  if char == ">"
    data+=1
  end
  if char == "<"
    data -= 1
  end
  if char == "+"
    cells[data]+= 1
    if cells[data] == MAX + 1
      cells[data] = 0
    end
  end
  if char == "-"
    cells[data]-= 1
    if cells[data] == -1
      cells[data] = MAX
    end
  end
  if char == "."
    print "#{cells[data].chr}"
  end
  if char == ","
    cells[data] = $stdin.gets[0]
  end
  if char == "["
    if cells[data] == 0
      count = 0
      inst += 1
      while input[inst].chr != "]" or count != 0
        if input[inst].chr == "]"
          count-= 1
        end
        if input[inst].chr == "["
          count+= 1
        end
        inst+= 1
      end
    end
  end
  if char == "]"
    if cells[data] != 0
      count = 0
      inst -= 1
      while input[inst].chr != "[" or count != 0
        if input[inst].chr == "["
          count-= 1
        end
        if input[inst].chr == "]"
          count += 1
        end
        inst-=1
      end
    end
  end
  inst+=1
end

No comments:

Post a Comment