Jeff_Birt wrote:
It would not be had to implement NUBMER? though, thinking out loud I guess you could do >NUMBER ( ud addr u -- ud addr2 u2 ) . If u2 is >0 then some part of the text was not a number.
One of the cool things about Forth is that you are allowed to assume that the users know what they are doing, so you don't have to protect them from everything (I remember, though I can't find it at the moment, a quote attributed to Chuck that went something like "we don't let idiots be brain surgeons, why should we let them program computers"). If you're using Forth and not, say, Go, you're probably in a situation where you have to run with scissors anyway. So for the conversion, maybe a word such as
Code:
: convertnumber ( addr u -- n )
>r >r 0. r> r> ( 0 0 addr u )
>number ( ud addr u )
2drop d>s ;
would be a possibility. You can use it with, say
Code:
s" 21" convertnumber
and it should have the single-cell number TOS, or -- and this is the cool part -- a 0 if it was a string. Define the game so that you need to guess a number between 1 and whatever, and the 0 marks some bad input if you really want to check for it.
I agree
>NUMBER looks scary at first -- my original reaction was, dude, WTF -- but it basically says "prime the pump with a double-cell number (usually just zero) and take the string. Return what you converted as a double-cell number, and the rest of the string if you found something that wasn't a number". Usually, you just toss out that last part, and convert the double-cell number to single-cell. While we're at it, I'm not sure if you want
Code:
VARIABLE BUFFER
but rather
Code:
CREATE BUFFER 20 ALLOT
because
CREATE will then just return the address (your code should work, it's just you expect a buffer to use
CREATE). Some systems have
BUFFER: to make this easier, see
https://forth-standard.org/standard/core/BUFFERColon (but not Gforth, it seems).
So if you want to be fancy, we could start off with
Code:
20 constant buffsize
create buffaddr buffsize allot
buffaddr buffsize accept ( u )
buffaddr swap ( addr u )
convertnumber ( n )
And then start guessing.