# Eine kleine Forth machine

**URL:** <https://discuss.kakoune.com/t/eine-kleine-forth-machine/1957>\
**Category:** Plugins\
**Tags:** scripting, language\
**Created:** [December 12, 2021, 4:36pm UTC](https://discuss.kakoune.com/t/eine-kleine-forth-machine/1957 "2021-12-12T16:36:02Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![almr](https://discuss.kakoune.com/user_avatar/discuss.kakoune.com/almr/32/934_2.png) [@almr](https://discuss.kakoune.com/u/almr)\
**Post date:** [December 12, 2021, 4:36pm UTC](https://discuss.kakoune.com/t/eine-kleine-forth-machine/1957/1 "2021-12-12T16:36:02Z")

</div>

> **[kstr0k / kak-stkmach · GitLab](https://gitlab.com/kstr0k/kak-stkmach)**
>
> A Forth implementation in pure Kakscript

I’ve written an (incomplete) [Forth](https://en.wikipedia.org/wiki/Forth_(programming_language)) interpreter on top of `kakscript`. This was a rather complex effort, which still needs more documenting, and I would like some feedback as time permits (@mawww ?).

To use, clone and symlink under `autoload` (or use `plug https://gitlab.com/kstr0k/kak-stkmach`)

After loading as above, select a name and boot a stack machine (multiple machines, with different prefixes, can boot):

```auto
require-module stkmach
stkmach-boot ff # create stack machine 'ff'
buffer *debug* # output shown in *debug* by default
ff-eval 3 2 + . # a simple op
echo -debug %opt{ff_builtins} # show available words
ff-interact # interactive Forth-ish buffer, use <a-ret>

```

Forth is a stack-oriented language. This implementation can do

- RPN arithmetic: `ff-eval 3 2 + 4 * . # =20; '.' means print`
- loops: `ff-eval 10 0 do i . loop # i = current counter`
- define “words”: `ff-eval : sqr dup * \; # duplicate, square, terminate def with \;`
  - `3 sqr sqr . # 81 # use def to square repeatedly`

- drive Kakoune (extension): `ff-eval 10 0 do i '' %{echo -debug} .kak-eval-top loop`

It also showcases `kakscript` intended and un-intended computability, and is a good way to benchmark the kakoune `C++` implentation. I have found some expected, but also some surprising slowdowns.

As an extension to Forth, strings can be placed on the stack using an empty-string (`''`) command, and be operated on (`.str+`, `.str=/.str<>`)

## Forth resources

- [Starting Forth](https://www.forth.com/starting-forth)
- [Forth primer by J. V. Noble](http://galileo.phys.virginia.edu/classes/551.jvn.fall01/primer.htm)
- [Gforth manual](https://gforth.org/manual/)
- [Forth Standard](https://forth-standard.org/standard/)
- [Wikipedia: Forth](https://en.wikipedia.org/wiki/Forth_(programming_language))
