<< Home | About Forth | About TurboForth | Download | Language Reference | Resources | Tutorials | YouTube >>


2LITERAL Search:

In Programming and Stack Management Words in 32-bit library

Word Name: 2LITERAL
Type: Immediate word
Data Stack Signature: d:x –
Return Stack Signature: --
Availability: V1.2
Description:

Pushes an in-line 32-bit value on the data stack at runtile.

Example:

1234567. 2. DU*
: TEST 2LITERAL D. ;
TEST (displays 2469134)

Here, we perform a calculation in interpret state: We take 1,234,567 and multiply it by 2, leaving it on the stack. We then start a colon definition (TEST) . 2LITERAL is then executed. 2LITERAL is an immediate word so it executes during the compilation of test; however 2LITERAL is not compiled into TEST. The behaviour of 2LITERAL is such that it takes a double value off the stack and compiles it into the colon definition as a literal, such that when TEST is subsequently executed, the literal value is pushed to the stack.

2LITERAL is normally used in conjunction with [ and ] to perform a calculation in interpret mode from within a colon definition and compile the result of the calculation into the colon definition, in order to avoid having to perform the calculation repeatedly at runtime.

For example:

: TEST 100 0 DO 1234567. 987. DU* D. LOOP ;

or

: TEST 100 0 DO [ 1234567. 987. DU* 2LITERAL ] D. LOOP ;

Both of the above examples display the number 1,218,517,629 in a loop 100 times, However, performing the same calculation repeatedly is wasteful.

The second example uses [ to temporarily drop into interpret mode, perform the calculation, compile it into TEST as a literal, and then resumes compilation with ]. Thus the second version runs faster, since the calculation was performed once at compile-time rather than 100 times at run-time.

Comment:

None

See Also: LITERAL 

<< Home | About Forth | About TurboForth | Download | Language Reference | Resources | Tutorials | YouTube >>