www.delorie.com/gnu/docs/gforth/gforth_117.html   search  
 
Buy GNU books!


Gforth Manual

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

5.12.1 Literals

The simplest and most frequent example is to compute a literal during compilation. E.g., the following definition prints an array of strings, one string per line:

 
: .strings ( addr u -- ) \ gforth
    2* cells bounds U+DO
	cr i 2@ type
    2 cells +LOOP ;  

With a simple-minded compiler like Gforth's, this computes 2 cells on every loop iteration. You can compute this value once and for all at compile time and compile it into the definition like this:

 
: .strings ( addr u -- ) \ gforth
    2* cells bounds U+DO
	cr i 2@ type
    [ 2 cells ] literal +LOOP ;  

[ switches the text interpreter to interpret state (you will get an ok prompt if you type this example interactively and insert a newline between [ and ]), so it performs the interpretation semantics of 2 cells; this computes a number. ] switches the text interpreter back into compile state. It then performs Literal's compilation semantics, which are to compile this number into the current word. You can decompile the word with see .strings to see the effect on the compiled code.

You can also optimize the 2* cells into [ 2 cells ] literal * in this way.

doc-[ doc-] doc-literal doc-]L

There are also words for compiling other data types than single cells as literals:

doc-2literal doc-fliteral doc-sliteral

You might be tempted to pass data from outside a colon definition to the inside on the data stack. This does not work, because : puhes a colon-sys, making stuff below unaccessible. E.g., this does not work:

 
5 : foo literal ; \ error: "unstructured"

Instead, you have to pass the value in some other way, e.g., through a variable:

 
variable temp
5 temp !
: foo [ temp @ ] literal ;


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

  webmaster     delorie software   privacy  
  Copyright 2003   by The Free Software Foundation     Updated Jun 2003