26 May 2023
Adventures in Forth/Stack Languages, part 1
Over the last week I have been playing with a Forth-like language that I have implemented (separately) in JavaScript and C.
I have embedded the JavaScript version below, and both versions are available on Codeberg: https://codeberg.org/DanielRHolland/forth-style-stack-lang.
Update (30th May 2023): The version embedded below is now the C version, compiled to WebAssembly.
Commands:
- Branching:
if <tokens> then -, pop value from stack. Iffalse/0, then skip all tokens between if and then. E.g.: f 1 1 = if 5 . then 8 . ; fwill output 5 followed by 8, and: f 0 if 5 . then 8 . ; fwill only output 8. (In forth,ifcan only be used inside user-defined functions, which is why the examples create a functionf, before immediately calling it.) - Arithmetic:
+ - / *, pop 2 values form the stack, apply op, push result back to stack - Pop:
.pop and print value - Peek:
peekpeek and print value - Stack manipulation:
dup(copy top item),swap(swap top two),drop(drop top item),rot(rotate top three: top becomes second, second becomes third, third becomes first). =pop two values, pushtrueto stack if they are equal, else pushfalsenotpop one value, pushtrueif it isfalse/0, else pushfalse: <name> <tokens> ;define new command, first word after:is the name, the following tokens will be inserted in its place when it is evaluated, up until the;.- E.g.
: countdown dup 0 = not if peek 1 - countdown then ;creates a command that can be called like the builtin commands are:5 countdown. - Use recursion to loop! (for now)
- Another example:
: dump dup if . dump then ;to pop and print the stack until the firstfalse/0value. - Multiplication implemented using addition and recursion:
: multrec over if rot swap over + rot 1 - swap multrec then ; : mult 0 multrec ; 6 8 mult .
- E.g.