Skip to content
Wolf Wejgaard edited this page Dec 26, 2019 · 47 revisions

Tcl & Forth

Tcl commands and Forth words are closely related. Both are called by their interpreters to compile or execute. Both, in effect, create the programming language, and both languages can be changed and extended by the programmer. The deciding difference is notation.

Tcl uses formal prefix notation for command arguments and an infix interpreter for math expressions. If we add a way to pass arguments on a stack, Tcl would be postfix, and a postfix Tcl is a Forth system: TclForth.

Study it with a few commands in the Forth console and the resulting Tcl code in the Code window (open it in the Setup menu).

Here is a Tcl command 'write' defined and used in the Forth console.

tcl proc write {text} {printnl $text}
tcl write "Hello World!"
Hello World!
ok

The initial word tcl passes the subsequent text to the Tcl-interpreter.

The same function as a code word in Forth:

Code Write { text -- }  printnl $text

TclForth compiles it into

proc Write {} {
set text [pop] ; printnl $text
}

and passes the code to the Tcl interpreter.

Tcl and thus TclForth names are case-sensitive.

"Hello World!" Write
Hello World!
ok

The only change needed to convert the Tcl command into a Forth word was the addition of "set text [pop] ;" in front of the code, which turns the stack argument 'text' into a local variable with this name. And we need a stack for the parameter.

The standard Forth definition of text messages is provided by

Compiler ."  
	PushText ; appendcode "print \[pop\] ; "

: Hello {} ." Hello world" ;


Forth Words

TclForth provides the standard set of Forth words as far as they make sense. Lookup the words in the files forth.fth and tk.fth. And note how the terms are applied in console.fth.

Knowing Tcl

To use TclForth, you will want some knowledge of Tcl

Clone this wiki locally