Search code examples
memoryforth

Forth: associate a name with a memory address


I use a word ->list that creates and returns an address. I don't always need to associate this address with a variable name, but I'd like that to be possible. For the moment, if I want to do so, this look like this:

.s <0>  ok
1 2 3 3 ->list .s <1> 140318466418488  ok
VARIABLE mylist  ok    
mylist ! .s <0>  ok  
mylist @ . 140318466418488  ok
mylist @ @ . 1  ok   
mylist @ 1 cells + @ . 2  ok
...

This provides an indirect addressing to access elements in ->list adress. Is it possible to create a variable which address is an already known address?


Solution

  • To associate a number (an address as well as any other number) with a name you can use constant. In your case:

    1 2 3 3 ->list constant mylist
    mylist @ . \ "1"
    

    Is it possible to create a variable which address is an already known address?

    In Forth, a variable is actually a constant that returns an address.

    For example, the word variable can be defined as follows:

    : variable ( "name" -- )
      align here 0 , constant
    ;
    

    So if you have the address of an already reserved cell, you can just use constant. For example:

    align here 123 ,  constant myvar
    myvar @ . \ "123"
    456 myvar !
    myvar @ . \ "456"