Question

After about several hours of trial and error, I couldn't figure how to do it... Here's the code I'm working on:

: format
    ( n ds -- )
    >r            cr .s
    dup              cr .s
    >r               cr .s
    abs              cr .s
    s>d              cr .s
    <# [char] bl hold #s r> sign #> cr .s
    r@               cr .s
    dup              cr .s
    c@               cr .s
    dup >r           cr .s
    chars +          cr .s
    char+            cr .s
    swap             cr .s 
    dup              cr .s
    >r               cr .s
    cmove            cr .s
    r> r> +          cr .s
    r>               cr .s
    c!
;

As an aside... isn't there an easier way to have printed output, something similar to printf would be great. Another possibility would be to specify space character as the first character of a s" " kind of string.

EDIT:

I found that I can do: s\" \040 test" in Gforth (though the manual says it's not standard). And s\" \x20 test" which is probably standard, but I don't quite understand where the part of the sentence which says whether it is standard or not relates. Still, I'd be happy to know how to combine it with pictured number output.

EDIT2

This is how I'd expect it be used:

create test 256 allot
s" prefix " test place
123 test format
s" suffix" test place+
test count type \ prefix 123 suffix
Was it helpful?

Solution

I think for this example you don't need to add the space within the <# #> stuff. You can define strings with leading or trailing spaces with s".

So if you start with

\ Push addresses and lengths for the prefix and the number
s" prefix "         \                             -- addr  u
123 s>d <# #s #>    \                      addr u -- addr u addr2 u2

The word that you want is something that concatenates them, for example:

: concatenate
    \ Moves the string addr2 u2 to the end of the string addr u
    >r >r                \        addr u addr2 u2 -- addr u
    dup >r over r> + r>  \                 addr u -- addr u addr+u addr2
    swap r@              \                 addr u -- addr u addr2 addr+u u2
    cmove r> + ;         \ addr u addr2 addr+u u2 -- addr u+u2

So if you call this and output the resulting string like this:

concatenate type

The output will be "prefix 123"

You could then apply the same word to the strings "prefix 123" and " suffix".

This doesn't use exactly the same memory locations as your example but it could be adapted, and just was the easiest way that I could demonstrate it.


In response to the comment, you seem to be pretty close to embedding characters in pictured output, I think you just need to remove the [char] e.g.

123 s>d <# # bl hold # bl hold # #>

Should generate a string like "1 2 3"

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top