phreda4.github.io

:r4 web site

View on GitHub

Print like C

:r4 has a library to generate character strings with number conversions, such as the printf of c. The idea is to use a string with indicators where they are replaced by values in the stack leaving a string with the values inserted to print or use in another purpose.

For example:

2 3 + 2 3 "%d + %d = %d" print

print

2 + 3 = 5

This way of printing values has a big counter and is that the amount of values that the stack has has to match the quantity of values that the chain needs. This complicates the static calculation when it is going to be compiled and there is no other way to do this check as if this feature were present in the base language and this is not true, it is just another library.

The way to do the conversion is by taking the direction of the string and traversing it looking for the indicators and triggering the conversion routines as the case may be.

The code is in lib/mprint.txt. here are the definitions to perform the conversion and leave the result in an internal buffer, calling the main word mprint, A word is also defined to count how many values of the stack you need, only used for compilation.

In the definition, two 4k buffers are used to allow an inclusion of a conversion, that is, to use the output of one formatted string as the input of another.

For every char call to ,emit

#control c0 c1 c2 c3 c4 c5 c6 c7 c8 c9 ca cb cc cd ce cf

:,emit | c --
	$25 <>? ( ,c ; ) drop
	c@+ $f and 2 << 'control + @ exec ;

When you need to jump to many different words it is best to use a list of vectors, since only with a single bifurcation of the code will I be in the word to execute.

Note here the way in which the key characters are chosen to jump to the corresponding routine, fix the 4 lower bits in the ascii table, make a list of the characters that fall in each slot and find the character (or characters) that correspond to each routine.