Search code examples
forth

In Forth, how many characters does 'expect' read?


The Forth-83 spec defines the word expect as follows:

      EXPECT       addr +n --                    M,83                 
           Receive characters and store each into memory.  The transfer
           begins at addr proceeding towards higher addresses one byte
           per character until either a "return" is received or until
           +n characters have been transferred.  No more than +n
           characters will be stored.  The "return" is not stored into
           memory.  No characters are received or transferred if +n is
           zero.  All characters actually received and stored into
           memory will be displayed, with the "return" displaying as a
           space.

So, it reads up to, but not including, a RETURN or EOL.

But without a terminator, and without returning the number of characters read, how do I know where the string ends?

Leo Brodie refers to a word accept, which does something very similar, which has the signature ( addr +n -- +m ). That does return the number of characters read, which is what I'd expect. But that's not in the spec...


Solution

  • The standard also defines SPAN, which tells you the number of characters read.

    Also note, that in the new standard this function is obsolete, use ACCEPT instead.