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.
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.
||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
||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
++ --- 2 ++ --- 2
Multiply 5 x 13
> ---- Move data pointer over to cell 1 (remember, it starts at 0!) +++++ ----- We want to run the below loop 5 times, so set the value at cell 1 to 5 [ ---- Loop start - ----- Subtract one from cell 1 (this is the cell that keeps track of how many times our loop runs) < ---------- Move data pointer back to cell 0, this is where we are storing our result +++++ +++++ +++ ---- Increment cell 0 13 times. > ------ Move data pointer back to cell 1, since it needs to be back there at the beginning of the loop when we subtract 1 from it again ] ---- End of loop < -------- Move back to cell 0, which is where we stored our result . ------ Print the contents of cell 0 in an ascii character. REMEMBER that this isn't a number, it's actually the letter "A", because "A" is at index 65 in the ASCII table! (and 5 x 13 is 65)
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.