stringloopsforth

Forth: Use 'I' as its value with 'CHAR'


I try to use special loop variable I with [CHAR]. With this minimal example:

: ex ( -- )
    10 0 DO
    [CHAR] I EMIT
    LOOP
;

I expected '0123456789' to be printed but -obviously- I get 'IIIIIIIIII'

Is there a way to replace I with its value before [CHAR] gets executed?


Solution

  • [CHAR] X is a character literal, that is represented by a code point of "X" on the stack. The expression [CHAR] X always produces the same value on the stack.

    If you want to print "1" given number 1 on the stack, you should get the code point of "1" at the first. You can do it as [char] 0 +.

    So you example becomes:

    : ex ( -- )
        10 0 DO
            I  [CHAR] 0 +  EMIT
        LOOP
    ;