Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I compare two strings in Forth?

And can I do it in an if statement or should I make a helper boolean variable? Here's the code I have so far. By the way, IOX@ is to get input from the user.

: var
compile: VARIABLE
complile: ;

: lock
compile: var realPass$
compile: realPass$ "password" !
compile: ." Enter Password: "
compile: var pass$
compile: IOX@ pass$ !
compile: var match
compile: realPass$=pass$ match ! Unknown token: realPass$=pass$
like image 847
Adam the Mediocre Avatar asked Jan 27 '26 14:01

Adam the Mediocre


1 Answers

The ANS FORTH word to compare strings is COMPARE (c-addr_1 u_1 c-addr_2 u_2 -- n). In FORTH a string is created with the s" word, and a string consists of a memory address and a length. This means that when you're comparing strings, you're providing to COMPARE the memory address and length of both strings.

The result of COMPARE is as follows: 0 if the two strings are equal, -1 for less-than, 1 for greater than. This is same as other languages that provide a comparator, or comparison operator. Note, in FORTH true is -1, so there is no value to checking the binary return of compare.

Generally Forth eschews explicit variables in favor of using the stack so using it with IF directly without an extra variable is fine.

: PWCHECK
  COMPARE
  IF ." Entry denied."
  ELSE ." Welcome friend." THEN
  CR
;

S" Hello" ok
S" Goodbye" ok
PWCHECK You are not wanted here. ok
S" Howdy"  ok
S" Howdy"  ok
PWCHECK Welcome friend. ok
like image 192
LogicG8 Avatar answered Jan 30 '26 09:01

LogicG8



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!