Skip to content

Commit 7d69245

Browse files
committed
Make interpreter includable and stubbable
1 parent cf844e8 commit 7d69245

File tree

2 files changed

+31
-22
lines changed

2 files changed

+31
-22
lines changed

interpreter.rb

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
# coding: utf-8
2+
3+
require_relative 'labyrinth'
4+
5+
case ARGV[0]
6+
when "-d"
7+
debug_level = 1
8+
when "-D"
9+
debug_level = 2
10+
else
11+
debug_level = 0
12+
end
13+
14+
if debug_level > 0
15+
ARGV.shift
16+
end
17+
18+
Labyrinth.run(ARGF.read, debug_level)

labyrinth.rb

Lines changed: 13 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -56,12 +56,15 @@ class ProgramError < Exception; end
5656

5757
OPERATORS.default = [:wall]
5858

59-
def self.run(src, debug_level=0)
60-
new(src, debug_level).run
59+
def self.run(src, debug_level=0, in_str=$stdin, out_str=$stdout, max_ticks=-1)
60+
new(src, debug_level, in_str, out_str, max_ticks).run
6161
end
6262

63-
def initialize(src, debug_level=false)
63+
def initialize(src, debug_level=false, in_str=$stdin, out_str=$stdout, max_ticks=-1)
6464
@debug_level = debug_level
65+
@in_str = in_str
66+
@out_str = out_str
67+
@max_ticks = max_ticks
6568

6669
@grid = parse(src)
6770
@height = @grid.size
@@ -95,7 +98,10 @@ def run
9598
@ip += @dir.vec
9699

97100
@tick += 1
101+
break if @max_ticks > -1 && @tick >= @max_ticks
98102
end
103+
104+
@max_ticks > -1 && @tick >= @max_ticks
99105
end
100106

101107
private
@@ -227,7 +233,7 @@ def process cmd
227233
byte = read_byte
228234
push_main(byte ? byte.ord : -1)
229235
when :output_char
230-
$> << (pop_main % 256).chr
236+
@out_str.print (pop_main % 256).chr
231237
when :input_int
232238
val = 0
233239
sign = 1
@@ -258,7 +264,7 @@ def process cmd
258264

259265
push_main(sign*val)
260266
when :output_int
261-
$> << pop_main
267+
@out_str.print pop_main
262268
when :output_newline
263269
puts
264270

@@ -403,23 +409,8 @@ def read_byte
403409
result = @next_byte
404410
@next_byte = nil
405411
else
406-
result = STDIN.read(1)
412+
result = @in_str.read(1)
407413
end
408414
result
409415
end
410-
end
411-
412-
case ARGV[0]
413-
when "-d"
414-
debug_level = 1
415-
when "-D"
416-
debug_level = 2
417-
else
418-
debug_level = 0
419-
end
420-
421-
if debug_level > 0
422-
ARGV.shift
423-
end
424-
425-
Labyrinth.run(ARGF.read, debug_level)
416+
end

0 commit comments

Comments
 (0)