Class: Nil::NilCommands

Inherits:
Object
  • Object
show all
Defined in:
lib/nil/nil_commands.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(code, mode = 'ascii') ⇒ NilCommands

Returns a new instance of NilCommands.



7
8
9
10
11
12
13
14
15
16
# File 'lib/nil/nil_commands.rb', line 7

def initialize(code, mode = 'ascii')
  @sp = 0
  @stack = [0] * 10_000
  @code_pointer = 0
  @loop_begin_pointer = 0
  @loop_end_pointer = 0

  @code = code
  @mode = mode
end

Instance Attribute Details

#codeObject (readonly)

Returns the value of attribute code.



3
4
5
# File 'lib/nil/nil_commands.rb', line 3

def code
  @code
end

#code_pointerObject (readonly)

Returns the value of attribute code_pointer.



3
4
5
# File 'lib/nil/nil_commands.rb', line 3

def code_pointer
  @code_pointer
end

#loop_begin_pointerObject (readonly)

Returns the value of attribute loop_begin_pointer.



3
4
5
# File 'lib/nil/nil_commands.rb', line 3

def loop_begin_pointer
  @loop_begin_pointer
end

#loop_end_pointerObject (readonly)

Returns the value of attribute loop_end_pointer.



3
4
5
# File 'lib/nil/nil_commands.rb', line 3

def loop_end_pointer
  @loop_end_pointer
end

#modeObject (readonly)

Returns the value of attribute mode.



3
4
5
# File 'lib/nil/nil_commands.rb', line 3

def mode
  @mode
end

#spObject (readonly)

Returns the value of attribute sp.



3
4
5
# File 'lib/nil/nil_commands.rb', line 3

def sp
  @sp
end

#stackObject (readonly)

Returns the value of attribute stack.



3
4
5
# File 'lib/nil/nil_commands.rb', line 3

def stack
  @stack
end

Instance Method Details

#runObject



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/nil/nil_commands.rb', line 18

def run
  while @code_pointer <= code.size
    case code[@code_pointer]
    when '.'
      if @mode == 'num'
        puts @stack[@sp]
      else
        print @stack[@sp].chr
      end
    when ','
      if @mode == 'num'
        @stack[@sp] = gets[0].to_i
      else
        @stack[@sp] = gets[0].ord
      end
    when '+'
      @stack[@sp] += 1
    when '-'
      @stack[@sp] -= 1 unless @stack[@sp] == 0
    when '>'
      @sp += 1
    when '<'
      @sp -= 1
    when '['
      @loop_begin_pointer = @code_pointer

      if @stack[@sp] <= 0
        @code_pointer = @loop_end_pointer
      end
    when ']'
      @loop_end_pointer = @code_pointer
      @code_pointer = (@loop_begin_pointer - 1)
    end
    @code_pointer += 1
  end
end