Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Brainfuck
- maximum_runtime: 16384
- new: (code,input,output_callback) =>
- @code=code
- @input=input
- @output_callback=output_callback
- @matrix={0}
- @memory_pointer=1
- @code_pointer=1
- shift_right: =>
- @memory_pointer += 1
- if @matrix[@memory_pointer]==nil
- @matrix[@memory_pointer]=0
- shift_left: =>
- @memory_pointer -= 1
- if @matrix[@memory_pointer]==nil
- @matrix[@memory_pointer]=0
- increment: =>
- @matrix[@memory_pointer]=(@matrix[@memory_pointer]+1)%256
- decrement: =>
- @matrix[@memory_pointer]=(@matrix[@memory_pointer]-1)%256
- jez_forward: =>
- if @get_value! == 0
- depth = 0
- while true
- @move_forward!
- switch @get_current_char!
- when "["
- depth += 1
- when "]"
- if depth == 0
- return nil
- else
- depth -= 1
- when nil
- return nil
- jnz_backward: =>
- if @get_value! != 0
- depth = 0
- while true
- @move_backward!
- switch @get_current_char!
- when "["
- if depth == 0
- return nil
- else
- depth -= 1
- when "]"
- depth += 1
- when ""
- return nil
- read_input: =>
- char = string.sub @input, 1, 1
- if char!=""
- @set_value string.byte char
- else
- @set_value 0
- @input = string.sub @input, 2
- move_forward: => @code_pointer+=1
- move_backward: => @code_pointer-=1
- get_char: (n) => string.sub @code, n, n
- get_current_char: => @get_char(@code_pointer)
- get_value: => @matrix[@memory_pointer]
- set_value: (value) => @matrix[@memory_pointer]=value
- append_input: (input) => @input ..= input
- step: =>
- ret = nil
- switch @get_current_char!
- when "["
- @jez_forward!
- when "]"
- @jnz_backward!
- when "+"
- @increment!
- when "-"
- @decrement!
- when "."
- ret=string.char @get_value!
- if @output_callback != nil
- @output_callback ret
- when ","
- @read_input!
- when ">"
- @shift_right!
- when "<"
- @shift_left!
- when ""
- return false
- @move_forward!
- ret
- run: =>
- output=""
- for i=1,@maximum_runtime
- step=@step!
- if step==false
- break
- elseif step!=nil
- output ..= step
- output
- print Brainfuck("--[>--->->->++>-<<<<<-------]>--.>---------.>--..+++.>----.>+++++++++.<<.+++.------.<-.>>+.","")\run!
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement