mirror of
https://github.com/adambard/learnxinyminutes-docs.git
synced 2024-12-23 17:41:41 +00:00
More rewording, mention ?do.
This commit is contained in:
parent
eb83f36015
commit
13a3c11394
@ -67,11 +67,10 @@ Forth, but most of what is written here should work elsewhere.
|
||||
|
||||
\ ------------------------------ Creating Words --------------------------------
|
||||
|
||||
\ Quite often one will want to write their own words.
|
||||
\ The `:` word sets Forth into compile mode until it sees the `;` word.
|
||||
: square ( n -- n ) dup * ; \ ok
|
||||
|
||||
\ The `:` word sets Forth into compile mode until it sees the `;` word.
|
||||
|
||||
\ We can view what a word does too:
|
||||
see square \ dup * ; ok
|
||||
|
||||
\ -------------------------------- Conditionals --------------------------------
|
||||
@ -101,19 +100,22 @@ myloop
|
||||
\ Hello!
|
||||
\ Hello! ok
|
||||
|
||||
\ `do` expects two numbers on the stack: the end number and the index number.
|
||||
\ `do` expects two numbers on the stack: the end number and the start number.
|
||||
|
||||
\ We can get the value of the index as we loop with `i`:
|
||||
: one-to-12 ( -- ) 12 0 do i . loop ; \ ok
|
||||
one-to-12 \ 0 1 2 3 4 5 6 7 8 9 10 11 12 ok
|
||||
: squares ( n -- ) 0 do i dup * . loop ; \ ok
|
||||
|
||||
\ `?do` works similarly, except it will skip the loop if the end and start
|
||||
\ numbers are equal.
|
||||
: squares ( n -- ) 0 ?do i dup * . loop ; \ ok
|
||||
10 squares \ 0 1 4 9 16 25 36 49 64 81 ok
|
||||
|
||||
\ Change the "step" with `+loop`:
|
||||
: threes ( n n -- ) do i . 3 +loop ; \ ok
|
||||
: threes ( n n -- ) ?do i . 3 +loop ; \ ok
|
||||
15 0 threes \ 0 3 6 9 12 ok
|
||||
|
||||
\ Finally, while loops with `begin` <stuff to do> <flag> `unil`:
|
||||
\ Indefinite loops with `begin` <stuff to do> <flag> `unil`:
|
||||
: death ( -- ) begin ." Are we there yet?" 0 until ; \ ok
|
||||
|
||||
\ ---------------------------- Variables and Memory ----------------------------
|
||||
@ -195,9 +197,15 @@ myfloatingvar f@ f. \ 4.4 ok
|
||||
\ specifically for that:
|
||||
clearstack
|
||||
|
||||
\ Clear the screen:
|
||||
page
|
||||
|
||||
\ Loading Forth files:
|
||||
\ s" forthfile.fs" included
|
||||
|
||||
\ You can list every word that's in Forth's dictionary (but it's a huge list!):
|
||||
\ words
|
||||
|
||||
\ Exiting Gforth:
|
||||
\ bye
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user