gforth cells : how to check there at least a free one

36 Views Asked by At

I get a code with this type of array setup :

create grid 16 cells allot
: init-grid grid 16 cells 0 fill ;

How can I check it while application is running. While application is running cells can be added (if adjacent using keyboards inputs) or not on X/Y (I do not use diagonals currently).

But a cell must be free to add a new value, each loop may compute the array with or without freeing a cell currently, so in some case I will get infinite loop on input error.

So I have to check in that order :

are all cell used ? no => check next loop of operation & input
are all cell used ? yes => force operation if possible & next loop else end input save square etc...

How can I check next operation is ok and will free one cell ?

1

There are 1 best solutions below

0
On

finally I managed to use a better way to do it; instead of reading it as vectors (vertical & distance) until I found 1st free cell (at least one)

I used and indexed all cells as an X/Y array instead so now I can use : builder :

\ in Forth, you do many things on your own. This word is used to define 2D arrays
: 2D-ARRAY ( height width )
        CREATE DUP ,
                * CELLS ALLOT
        DOES> ( y x baseaddress )
                ROT    ( x baseaddress y )
                OVER @ ( x baseaddress y width )
                *      ( x baseaddress y*width )
                ROT    ( baseaddress y*width x )
                + 1+ CELLS +
;

and then

: findfreecell ( index -- addr )
        0 0 tab SWAP ( curr-addr index )
        0 0 tab @ 0<> IF 
                1+ 
        THEN
        0 ?DO ( find the next free space index times )
                BEGIN
                        CELL+ DUP @ 0=
                UNTIL
        LOOP
;

this way I am sure there is free cells for next operations & I can call the operation procedure.