You can loop through lists and dictionaries using the for keyword. For example, do this to go through a list:
for animal in animals
echo animal
endfor
And here's you iterating through a dictionary:
for animal in keys(animal_names)
echo 'This ' . animal . '''s name is ' . animal_names[animal]
endfor
You can also access both the key and the value of the dictionary simultaneously using items:
for [animal, name] in items(animal_names)
echo 'This ' . animal . '''s name is ' . name
endfor
You can control the iteration flow with continue and break. Here's an example of using break:
let animals = ['dog', 'cat', 'parrot']
for animal in animals
if animal == 'cat'
echo 'It''s a cat! Breaking!'
break
endif
echo 'Looking at a ' . animal . ', it''s not a cat yet...'
endfor
The output from this would be the following:
And this is how you would use continue:
let animals = ['dog', 'cat', 'parrot']
for animal in animals
if animal == 'cat'
echo 'Ignoring the cat...'
continue
endif
echo 'Looking at a ' . animal
endfor
And the output from this would be the following:
while loops are also supported:
let animals = ['dog', 'cat', 'parrot']
while !empty(animals)
echo remove(animals, 0)
endwhile
This will print the following:
You can use break and continue the same way with while loops:
let animals = ['cat', 'dog', 'parrot']
while len(animals) > 0
let animal = remove(animals, 0)
if animal == 'dog'
echo 'Encountered a dog, breaking!'
break
endif
echo 'Looking at a ' . animal
endwhile
This will output the following: