Sampi

Home Older Versions Documentation Changelog Learn


Loops

Suppose you want to say "Hello!" 5 times? Simple! Just run:


say("Hello!")
say("Hello!")
say("Hello!")
say("Hello!")
say("Hello!")
        

OK, but what if you want it to run 1,000 times? There is a better option. This is where you would use a loop. A loop does what it says. It repeats code a known number of times.


repeat 5:
    say("hello")
end
        

If you want to know what iteration you are on, use as and the name of the variable you want. It is common to use the letter i, short for iterator.


repeat 5 as i:
    say(i)
end
        

What if you want to repeat code an unknown number of times? That is where until loops come in. They repeat code until a condition is true. Here is a program where you guess the password:


set guess to ""

until guess = "password"
    say("That is not the password.")
    set guess to ask("What is the password? ")
end

say("You found the password!")
        

The code will repeat until guess = "password". With until loops, you can make an infinite loop. until true An infinite loop will never end. This can be useful, but be careful.


Previous Next