Skip to reading
BASIC Scripting

Count with FOR and FOR EACH

Edition 0.86.4.1 HF1

0.86.4.1 Hotfix 1 edition. Earlier lessons and screenshots retain their original version context; revised references and supplements describe the newer behavior.

Download PDFView PDF page

THE BASIC LANGUAGE

Use a numeric FOR when you know the first and last numbers. Use FOR EACH when the job is to visit the entries in a collection.

Code example
FUNCTION Run()
    DIM total = 0
    FOR n = 5 TO 1 STEP -2
        total += n
    NEXT
    RETURN total
END FUNCTION

The loop visits 5, 3 and 1. Both endpoints are included when the step lands on them. total ends at 9. STEP defaults to 1 and must be nonzero.

Code example
FUNCTION Run()
    DIM names = ["Ada", "Ben", "Cy"]
    DIM chosen = ""
    FOR EACH person, i IN names
        IF i = 1 THEN
            CONTINUE
        END IF
        chosen = chosen & person
    NEXT
    RETURN chosen
END FUNCTION

The first item has index 0. On index 1, CONTINUE skips Ben and advances to the next item. The result is AdaCy. For a dictionary, FOR EACH visits keys. Its optional index counts visits.

Page 12 of 86Permalink
Go to page