Skip to content

Instantly share code, notes, and snippets.

@lukewilson2002
Created March 29, 2018 23:04
Show Gist options
  • Save lukewilson2002/62a43522effea880993289c167c4b265 to your computer and use it in GitHub Desktop.
Save lukewilson2002/62a43522effea880993289c167c4b265 to your computer and use it in GitHub Desktop.
Brainfuck interpreter written in Odin.
import "core:fmt.odin"
interpret :: proc(program: string) {
tape: [30000]u8 = 0;
ptr := 0;
index := 0;
for index < len(program) {
switch program[index] {
case '+': tape[ptr] += 1;
case '-': tape[ptr] -= 1;
case '>': ptr += 1;
case '<': ptr -= 1;
case ',': continue; // unimplemented
case '.': fmt.printf("%c", tape[ptr]);
case '[':
if tape[ptr] == 0 {
nesting := 1;
for nesting != 0 {
index += 1;
switch program[index] {
case '[': nesting += 1;
case ']': nesting -= 1;
case:
}
}
}
case ']':
if tape[ptr] != 0 {
nesting := 1;
for nesting != 0 {
index -= 1;
switch program[index] {
case '[': nesting -= 1;
case ']': nesting += 1;
case:
}
}
}
case:
}
index += 1;
}
}
HELLO_WORLD :: string("++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.");
main :: proc() {
interpret(HELLO_WORLD);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment