Created
August 17, 2012 17:16
-
-
Save squidarth/3380731 to your computer and use it in GitHub Desktop.
Brainfuck Interpreter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def parseBrainFuck(string, in_while = false) | |
global_stack = [] | |
curr_index = 0 | |
parse_index = 0 | |
parse_lookup = { | |
"+" => lambda {global_stack[curr_index] += 1}, | |
"-" => lambda {global_stack[curr_index] -= 1}, | |
">" => lambda {curr_index += 1}, | |
"<" => lambda {curr_index -= 1}, | |
"." => lambda {puts global_stack[curr_index]} | |
} | |
until done | |
while parse_index < string.length | |
if string[parse_index] == "[" | |
start_index = parse_index | |
bracket_count = 1 | |
until bracket_count == 0 | |
if string[parse_index] == "]" | |
bracket_count -= 1 | |
elsif string[parse_index] == "[" | |
bracket_count += 1 | |
end | |
parse_index += 1 | |
end | |
inner_string = string[start_index + 1, parse_index - 2] | |
parseBrainFuck(inner_string, true) | |
end | |
if parse_lookup[string[parse_index]] | |
parse_lookup[string[parse_index]].call | |
end | |
parse_index += 1 | |
end | |
if !in_while || global_stack[curr_index].nil? | |
done = true | |
else | |
parse_index = 0 | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment