Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gforth 2constant; explanation of the content?

Tags:

forth

gforth

in gforth, when I want to see the inner of the word 2constant , I use the command

see 2constant 

then the output is..

: 2Constant  
  Create 2, 140549207084808 (does>2) ;

I could not find so far a clear explanation after "2,". I am a beginner in forth and need to understand this, in order to migrate the word 2constant in a board, which forth has no 2constant word. Any hint is welcome.

like image 899
floppy_molly Avatar asked Sep 06 '25 03:09

floppy_molly


1 Answers

If I didn't have 2CONSTANT defined I'd define:

: my2constant    \ d <name> --
  CREATE 2, DOES> 2@ ;

In GFORTH:

see 2CONSTANT 
: 2Constant  
  Create 2, 140453810216712 (does>2) ; ok
see my2CONSTANT 
: my2constant  
  Create 2, 140453810521432 (does>2) ; ok
HERE .      140453810521464  ok
\ the constant seems related to the dictionary pointer when the word is defined.
\ I'd guess the number is related to the code address which `(does>2)` executes 
\ when an instance of 2CONSTANT is executed. 

\ The words defined by 2CONSTANT match the original definition
123 456 my2constant test  ok
test . .  456 123  ok
see test 
create test  
DOES> 2@ ; ok 

123 456 2CONSTANT testg  ok

see testg 
create testg  
DOES> 2@ ; ok

Added following the comment

: 2,  , , ; \ d -- ; Place d into the dictionary.

: 2@  DUP CELL+ @ SWAP @ ;  \ a -- lo hi ;  

: 2CONSTANT   \ d <name> -- ; Create a 2constant with the name <name>
              \ does> -- d
  CREATE 2, DOES> 2@ ;

\ For completeness 
: 2!  SWAP OVER ! CELL+ ! ;  \ lo hi a -- ;  a contains hi a +cell contains lo

: 2VARIABLE   \ <name> -- ; Create a double variable in the dictionary
              \ does> -- a
  CREATE 0 , 0 , DOES> ;

Testing

123 456 2CONSTANT test  ok
test .s <2> 123 456  ok

2VARIABLE vtest  ok
789 1011 vtest 2! .S <2> 123 456  ok
vtest 2@ .S <4> 123 456 789 1011  ok

I can't make sense of the code in the comment. It almost does 2! but would overwrite the first value stored with the second. I can't see why the compilation state is relevant.

: G_2CONSTANT   \ lo hi addr -- ; Assumed to make it do something
  DUP >R                    \ lo hi addr r: addr
  STATE @ IF 0 , 0 , THEN   \ Why ?
  R>                        \ lo hi addr addr
  !                         \ lo hi  ; Store addr at addr ?
  ! ;                       \ Store lo at hi.  Causes the error

: G_CONSTANT   \ lo hi addr -- ; Equivalent to 2!
  DUP >R ! R> CELL+ ! ;

CREATE is required if 2CONSTANT is to define a new word and the DOES> action of the word is required to recover the stored values.

like image 75
Tls Chris Avatar answered Sep 07 '25 22:09

Tls Chris