Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ASCII EQUS " \t\n\r !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz\{|}~"
- bf: MACRO
- ; Run a brainfuck program.
- ; bf source[, input]
- ; point to the first program char
- src_i = 1
- src_len = STRLEN("\1")
- ; point to the first input char
- in_p = 1
- in_len = 0
- if _NARG > 1
- in_len = STRLEN("\2")
- endc
- ; point to the first cell
- mem_p = 0
- mem_len = 32768
- cell_size = 256
- ; initialize 32768 memory cells to 0s
- for i, mem_len
- mem{d:i} = 0
- endr
- ; run the program
- rept $7fffffff
- if src_i > src_len
- break
- endc
- ; get the current source code character
- x = STRSUB("\1", src_i, 1)
- ; increment the current cell
- if x == "+"
- mem{d:mem_p} = (mem{d:mem_p} + 1) % cell_size
- ; decrement the current cell
- elif x == "-"
- mem{d:mem_p} = (mem{d:mem_p} - 1) % cell_size
- ; move to the next cell
- elif x == ">"
- mem_p = (mem_p + 1) % mem_len
- ; move to the previous cell
- elif x == "<"
- mem_p = (mem_p - 1) % mem_len
- ; output the current cell
- elif x == "."
- print STRSUB("{ASCII}", mem{d:mem_p} + 1, 1)
- ; input the current cell
- elif x == ","
- if in_p <= in_len
- mem{d:mem_p} = STRSUB("\2", in_p, 1)
- in_p = in_p + 1
- else
- mem{d:mem_p} = cell_size - 1 ; EOF
- endc
- ; begin while loop
- elif x == "["
- if mem{d:mem_p} == 0
- if !DEF(pair{d:src_i})
- ; find the corresponding ']' after the '['
- depth = 1
- for i, src_i + 1, src_len + 1
- y = STRSUB("\1", i, 1)
- depth = depth + (y == "[") - (y == "]")
- if depth == 0
- break
- endc
- endr
- if i == src_len
- fail "[ without ]"
- endc
- pair{d:src_i} = i
- endc
- src_i = pair{d:src_i}
- endc
- ; end while loop
- elif x == "]"
- if mem{d:mem_p} != 0
- if !DEF(pair{d:src_i})
- ; find the corresponding '[' before the ']'
- depth = 1
- for i, src_i - 1, 0, -1
- y = STRSUB("\1", i, 1)
- depth = depth - (y == "[") + (y == "]")
- if depth == 0
- break
- endc
- endr
- if i == 0
- fail "] without ["
- endc
- pair{d:src_i} = i
- endc
- src_i = pair{d:src_i}
- endc
- endc
- ; move to the next source code character
- src_i = src_i + 1
- endr
- ENDM
- ; hello world
- bf ++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.
- ; echo
- bf \,+[-.\,+], HELLO WORLD!\n
Advertisement
Add Comment
Please, Sign In to add comment