pmg
pmg

Reputation: 108978

Using HERE in Forth for temporary space

I'm writing a game in Forth (for learning purposes).

The game is played on a "10 cell board". I'm trying new stuff so I did

here 10 [char] - fill

to set up the space for the board.
Then, to play 'X' in position 3

[char] X here 3 + c!

This has been working fine, but raises the question

Is this OK?
What if the board was a million cells wide?

Thanks

Upvotes: 3

Views: 205

Answers (1)

ruvim
ruvim

Reputation: 8564

The described approach has the certain environmental dependencies, so your program just have to match the environmental restriction on programs of your Forth system (i.e. that you use).

1. Size of the data space

The word UNUSED returns "the amount of space remaining in the region addressed by HERE". So, a program can check the available space.

Also, according to the subsection 4.1.3 Other system documentation of the Forth Standard:

A system shall provide the following information: [...] program data space available, in address units;

So, you have just to check whether your Forth system provides enough data space for you program, and how the available data space can be configured (if any).

2. Transient regions

In the general case, it is not safe for a portable program to use the data space without reserving it.

According to the section 3.3.3.6 Other transient regions of the Forth Standard, the contents of the data space regions identified by PAD, WORD, and #> may become invalid after the data space is allocated. Сonsequently, the contents of the region identified by HERE may become invalid after the contents of the regions identified by PAD, WORD, and #> are changed.

See also A.3.3.3.6 Other transient regions:

In many existing Forth systems, these areas are at HERE or just beyond it, hence the many restrictions.

Moreover, some Forth systems may use the region identified by HERE in internal purposes during translation. E.g. Gforth 0.7.9 uses this region when decoding escaped strings. The phrase:

s\" test\-passed" cr here over type cr type cr

outputs:

test-passed
test-passed

So, you have to check the restrictions of your Forth system whether you may use the region identified by HERE without reserving the space (and in what conditions).

Upvotes: 4

Related Questions