Search code examples
forth

Why are all words in Forth by default global?


I am learning Forth. Why are all words in the language by default global?

Correct me please if I am naming keys of dictionary correctly -- words.


Solution

  • If we are talking about scoping, I think the reason is that the global scope is just the simplest approach that is available anywhere.

    Yes, by default all standard and user-defined words have global scope. But for each word its scope begins at its definition end only (so on redefinition, the previous word can be used in the definition of the new word with the same name). And the scope of local variables is limited by the definition body where these variables are declared.

    Forth also provides more advanced techniques to control words visibility.

    The words are grouped into word lists (a kind of namespaces). And any part of a program can be excluded from the scope of a word list (i.e. the words from this word list). For that this word list should be excluded from the search order at the start of this part of the program (and reverted at the end). Likewise, any part of a program can be included into the scope of a word list by including this word list into the search order (and reverting at the end). Of course, we have the effect of name masking in this case.

    Also many Forth systems provide an API that allows to use the names that are partially qualified by word lists. For example: module1::submodule2::word3, where module1 is a word that is available by the search order, and that returns a word list identifier wid1. submodule2 is a word that is defined in the word list wid1, and that returns a word list identifier wid2, word3 is a word that is defined in the word list wid2. (See RESOLVE-PQNAME word in my implementation as a reference).

    To have a shorter access to some module, you can define your synonym, e.g. module1::submodule2 constant m and use prefix m:: to access the words from this sub-module as m::word3.