Define a primitive data type: Difference between revisions

m
syntaxhighlight doesn't have a default lang, need to provide one
m (auto syntax highlight fix)
m (syntaxhighlight doesn't have a default lang, need to provide one)
Line 751:
=== Method 1: Safe Integer Store operators===
Forth is a fetch and store based virtual machine. If we create a safe version of store (!) the programmer simply uses this operator rather than the standard store operator.
<syntaxhighlight lang="text">DECIMAL
: CLIP ( n lo hi -- n') ROT MIN MAX ;
: BETWEEN ( n lo hi -- flag) 1+ WITHIN ;
Line 761:
! ;</syntaxhighlight>
Testing
<syntaxhighlight lang="text">VARIABLE X
7 X SAFE! X ? 7 ok
12 X CLIP! X ? 10 ok
Line 774:
=== Method 2: redefine standard "store" operator as DEFER word ===
Using the code in Method 1, we can re-define the store (!) operator to be switchable.
<syntaxhighlight lang="text">DECIMAL
: FAST! ( n addr -- ) ! ; ( alias the standard version)
 
Line 785:
 
Testing
<syntaxhighlight lang="text">VARIABLE Y
 
LIMITS-OFF ok
Line 811:
A VALUE defines a numerical data type that returns it's value rather than an address (pointer) like a variable.
We can create a word that assigns a number to a VALUE but tests for out of range errors.
<syntaxhighlight lang="text">: (->) ( n <text> -- )
OVER 1 10 BETWEEN 0= ABORT" out of range!"
>BODY ! ;
Line 822:
 
Test
<syntaxhighlight lang="text">0 VALUE Z ok
99 TO Z ok ( normal assignment)
Z . 99 ok
10,327

edits