complexpr/examples/bf.cxpr

68 lines
1.7 KiB
Plaintext
Raw Normal View History

2022-09-10 21:19:23 +00:00
while true {
print("bf> ");
let program = input();
let tape = [0]*256;
let ptr = 0;
let i = 0;
while i < len(program) {
let op = program[i];
if op == '+' {
tape[ptr] += 1;
if tape[ptr] >= 256 {
tape[ptr] -= 256;
}
} elif op == '-' {
tape[ptr] -= 1;
if tape[ptr] < 0 {
tape[ptr] += 256;
}
} elif op == '>' {
ptr += 1;
} elif op == '<' {
ptr -= 1;
} elif op == '.' {
print(chr(tape[ptr]));
} elif op == ',' {
tape[ptr] = ord(input()[0]);
} elif op == '[' {
if tape[ptr] == 0 {
let depth = 0;
2022-09-11 05:01:53 +00:00
while true {
2022-09-10 21:19:23 +00:00
i += 1;
if program[i] == ']' {
if depth == 0 {
2022-09-11 05:01:53 +00:00
break;
2022-09-10 21:19:23 +00:00
}
depth -= 1;
} elif program[i] == '[' {
depth += 1;
}
}
}
} elif op == ']' {
if tape[ptr] != 0 {
let depth = 0;
let running = true;
2022-09-11 05:01:53 +00:00
while true {
2022-09-10 21:19:23 +00:00
i -= 1;
if program[i] == '[' {
if depth == 0 {
2022-09-11 05:01:53 +00:00
break;
2022-09-10 21:19:23 +00:00
}
depth -= 1;
} elif program[i] == ']' {
depth += 1;
}
}
}
}
if ptr >= len(tape) {
tape += [0]*256;
}
i += 1;
}
println("");
2022-09-11 17:02:18 +00:00
}