Let's get right to it: this week's Snack Break problem involves writing a compiler for a computer language. Don't worry, though! It's an extremely basic programming language with few rules and instructions.
Brain***k is a funny little language. It should be a fun task to implement a version of it in Lua! From Wikipedia:
Brain***k is an esoteric programming language created in 1993 by Urban Müller, and notable for its extreme minimalism.
The language consists of only eight simple commands and an instruction pointer. While it is fully Turing-complete, it is not intended for practical use, but to challenge and amuse programmers.
You can use this online Brain***k compiler to get some more examples and experiment with the language.
Breakdown
The concept of the language is simple. Imagine you have a row of cells or an array. The data pointer points to an index of this array. Two instructions in the language can increment or decrement the data pointer, so as to adjust the active index of the array. Two other instructions can increment or decrement the value at the index, e.g. data[pointer] = data[pointer] + 1
.
Here is a list of all the instructions in the language. Every instruction in Brain***k is one-character long, so that makes it easy to parse.
Character |
Meaning |
> |
Increment the data pointer by one. |
< |
Decrement the data pointer by one. |
+ |
Increment the value at the data pointer by one. |
- |
Decrement the value at the data pointer by one. |
. |
Output the byte at the data pointer as an ASCII character (Lua's string.char will come in handy for this!) |
[ |
Loop start: If the value at the current data pointer is not zero, continue. If it is zero, jump to after the matching ] |
] |
Jump to the matching [ |
Any other characters that aren't in the list above are ignored.
Examples of the language in action
Add 2 + 2
Multiply 5 x 13
Hello World
1 | ++++++++ [ >++++ [ >++>+++>+++>+<<<<- ] >+>+>->>+ [ < ] <- ] >>.> |
Advanced challenge
Add the final instruction, a ,
, which accepts one byte of input from the user and stores it in the value of the current data pointer.
Good luck!
Commentary
Leave a Comment