Search code examples
forthgforth

What does the `type` word do?


Given the following function, (borrowed from Rosetta Code)

: (echo) ( sock buf -- sock buf )
  begin
    cr ." waiting..."
    2dup 2dup size read-socket nip
    dup 0>
  while
    ."  got: " 2dup type ( <-- HERE )
    rot write-socket
  repeat
  drop drop drop ;

What does type do in,

."  got: " 2dup type

Solution

  • type is a word. You can find the list of the words here

    type       c-addr u –         core       “type”
    

    If u>0, display u characters from a string starting with the character stored at c-addr.

    In this case you have

    128 constant size
    create buf size allot
    

    Then you set buf with read-socket. This type it to a string and prints it out.

    Returns a memory address for the string and the size.

    cr s" foo bar " .s
    

    Output:

    <2> 94085808947584 8  ok
    

    Here we provide the memory address and size to type and get "foo bar"

    cr 94085808947584 8 type
    

    Output:

    foo bar  ok