Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is a Forth value different from a variable?

Tags:

forth

Reading the Gforth manual, a value can be changed using the word TO, so how is it different than a variable?

https://gforth.org/manual/Values.html

like image 763
Olle Härstedt Avatar asked Mar 03 '26 04:03

Olle Härstedt


2 Answers

VALUE takes an initial value, and the created word puts the value directly on the stack like CONSTANT. The value can still be changed using TO. Word definitions in many Forths using VALUE's will be smaller, because they just need to reference the created word and not !.

5 VALUE TERRYS
TERRYS . 5 ok

VARIABLE just reserves space for the value, uninitialised, and the created word puts the address of the variable on the stack instead.

VARIABLE TERRYS
5 TERRYS !
TERRYS @ . 5 ok

VARIABLE is useful when you want to take the address of the variable, and VALUE is useful when you don't need to.

If you want to initialise the variable, and be able to take the address, it is actually easier to just use CREATE and ,, like so:

CREATE TERRYS 5 ,
TERRYS @ . 5 ok
like image 82
Veltas Avatar answered Mar 07 '26 01:03

Veltas


if you define a word as 5 value A

when you type A

you get 5 put on the stack

when you type variable A

when you type A

you get an address put on the stack

to get the value inside, you use @

to write to it, you use !

value creates a word that puts a value on the stack

variable creates a word that puts an address on the stack

like image 23
Olle Härstedt Avatar answered Mar 06 '26 23:03

Olle Härstedt