diff options
author | Araq <rumpf_a@web.de> | 2013-01-23 13:23:31 -0800 |
---|---|---|
committer | Araq <rumpf_a@web.de> | 2013-01-23 13:23:31 -0800 |
commit | 5568f85449cb193a0b81f0f3cb6c189cf0b4164c (patch) | |
tree | 6d066c38f99941300476212a5cc094305b8a7b4b /doc | |
parent | 0fac291eaa6a7409345ab828f325619f4d8a6eef (diff) | |
parent | 958f20aa1ab5c511de73eb397be5fa8d0f0ff085 (diff) | |
download | Nim-5568f85449cb193a0b81f0f3cb6c189cf0b4164c.tar.gz |
Merge pull request #311 from gradha/pr_documents_two_variable_for_loop
Documents two-variable for loop with sequences.
Diffstat (limited to 'doc')
-rwxr-xr-x | doc/tut1.txt | 25 |
1 files changed, 25 insertions, 0 deletions
diff --git a/doc/tut1.txt b/doc/tut1.txt index 8edd5c33c..746d11f01 100755 --- a/doc/tut1.txt +++ b/doc/tut1.txt @@ -349,6 +349,7 @@ provides. The example uses the built-in ``countup`` iterator: echo("Counting to ten: ") for i in countup(1, 10): echo($i) + # --> Outputs 1 2 3 4 5 6 7 8 9 10 on different lines The built-in ``$`` operator turns an integer (``int``) and many other types into a string. The variable ``i`` is implicitly declared by the ``for`` loop @@ -362,6 +363,7 @@ the same: while i <= 10: echo($i) inc(i) # increment i by 1 + # --> Outputs 1 2 3 4 5 6 7 8 9 10 on different lines Counting down can be achieved as easily (but is less often needed): @@ -369,6 +371,7 @@ Counting down can be achieved as easily (but is less often needed): echo("Counting down from 10 to 1: ") for i in countdown(10, 1): echo($i) + # --> Outputs 10 9 8 7 6 5 4 3 2 1 on different lines Since counting up occurs so often in programs, Nimrod also has a ``..`` iterator that does the same: @@ -1202,6 +1205,28 @@ raised) for performance reasons. Thus one should use empty sequences ``@[]`` rather than ``nil`` as the *empty* value. But ``@[]`` creates a sequence object on the heap, so there is a trade-off to be made here. +The ``for`` statement can be used with one or two variables when used with a +sequence. When you use the one variable form, the variable will hold the value +provided by the sequence. The ``for`` statement is looping over the results +from the ``items()`` iterator from the `system <system.html>`_ module. But if +you use the two variable form, the first variable will hold the index position +and the second variable will hold the value. Here the ``for`` statement is +looping over the results from the ``pairs()`` iterator from the `system +<system.html>`_ module. Examples: + +.. code-block:: nimrod + for i in @[3, 4, 5]: + echo($i) + # --> 3 + # --> 4 + # --> 5 + + for i, value in @[3, 4, 5]: + echo("index: ", $i, ", value:", $value) + # --> index: 0, value:3 + # --> index: 1, value:4 + # --> index: 2, value:5 + Open arrays ----------- |