\ Listing 3. Range checking for the arrays needs arrays.seq \ The -1st array element contains the number of elements in the array. \ redefine ARRAY, to lay down such -1st element. : array, ( a[n-1]...a[0] n -- ) ( align ) dup , array, ; \ The checking word to be used with [] : _? ( index arr -- ) \ ensure that the index is correct 2dup -1 swap [] < if over 0< 0= if exit then then cr ." *** invalid index " over . ." for the array at " dup u. cr ; \ To enable range checking, we can \ either globally redefine [] , \ or redefine it in the module's dictionary, \ or find a new name (e.g. /[] ) for the protected version of [] , \ or redefine [] and use /[] for the original version of [] , \ or use _? every time we need a check. \ \ For example, we can define \ : /[] _? [] ; \ if we want /[] to do range checking, and \ : /[] ?comp compile [] ; immediate \ if we want it to compile [] : []len ( index2 2array -- len1 ) _? 2dup -1 swap [] 1- = if cr ." *** []LEN does not work for the last ( " over . ." ) subarray (of array at " dup u. ." )" cr then []len 1- ; : [] _? [] ; : []! _? []! ; : []^ _? []^ ; \ NB: we have to recompile .ARRAY and .2ARRAY as well, \ unless we want them to show 1 extra cell beyond each line. \ \s Examples showlines \ 1-dimensional array: 11 22 33 44 4 array, constant y -1 y [] . 0 y [] . 1 y [] . 3 y [] . 4 y [] . \ 2-dimensional array \ The last, delimiting, subarray is needed for []len \ to calculate the length properly \ NB: we use the same syntax but *different* versions of array words. 1 2 3 4 5 5 array, 6 7 8 9 4 array, 10 11 12 3 array, 0 array, 4 array, constant x 0 0 x [] [] . -2 0 x [] [] . 0 -2 x [] [] . -1 -2 x [] [] . 0 x []len . -1 x []len . 3 x []len . 4 x []len . off> listvar