Jump to content

Define a primitive data type: Difference between revisions

Line 559:
: SAFE! ( n addr -- )
OVER 1 10 BETWEEN 0= ABORT" out of range!"
! ;</LANG>
Testing
\ testing
<LANG>VARIABLE X
7 X SAFE! X ? 7 ok
12 X CLIP! X ? 10 ok
Line 582:
: LIMITS-ON ( -- ) ['] SAFE! IS ! ;
: LIMITS-OFF ( -- ) ['] FAST! IS ! ;
: CLIPPING-ON ( -- ) ['] CLIP! IS ! ; </LANG>
 
Testing
<LANG>VARIABLE Y
 
VARIABLE Y
\ tests at console
LIMITS-OFF ok
1 Y ! Y ? 1 ok
Line 607 ⟶ 608:
$7FAD4460 c(abort")
</LANG>
=== Method 3: Create a safe VALUE assignment operator===
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.
<LANG>: (->) ( n <text> -- )
OVER 1 10 BETWEEN 0= ABORT" out of range!"
>BODY ! ;
 
: -> ( n -- )
STATE @
IF POSTPONE ['] POSTPONE (->) \ compiling action
ELSE ' (->) \ interpret action
THEN ; IMMEDIATE</LANG>
 
Test
<LANG>0 VALUE Z ok
99 TO Z ok ( normal assignment)
Z . 99 ok
99 -> Z ( safe assignment)
:43: out of range!
99 -> >>>Z<<<
Backtrace:
$7FAA2B0C throw
$7FAD4570 c(abort")
$7FAD45DC (->)</LANG>
 
=={{header|Fortran}}==
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.