Title here
Summary here
_range_ iterates over elements in a variety of built-in data structures. Let’s see how to use `range` with some of the data structures we’ve already learned.
Here we use `range` to sum the numbers in a slice. Arrays work like this too.
```angelscript
void main() {
int[] nums = {2, 3, 4};
int sum = 0;
for (uint i = 0; i < nums.length(); i++) {
sum += nums[i];
}
println("sum: " + sum);
}
range
on arrays and slices provides both the index and value for each entry. Above we didn’t need the index, so we ignored it with the blank identifier _
. Sometimes we actually want the indexes though.
void main() {
int[] nums = {2, 3, 4};
for (uint i = 0; i < nums.length(); i++) {
if (nums[i] == 3) {
println("index: " + i);
}
}
}
range
on map iterates over key/value pairs.
void main() {
dictionary kvs;
kvs.set("a", "apple");
kvs.set("b", "banana");
array<string> keys = kvs.getKeys();
for (uint i = 0; i < keys.length(); i++) {
string key = keys[i];
string value;
kvs.get(key, value);
println(key + " -> " + value);
}
}
range
can also iterate over just the keys of a map.
void main() {
dictionary kvs;
kvs.set("a", "apple");
kvs.set("b", "banana");
array<string> keys = kvs.getKeys();
for (uint i = 0; i < keys.length(); i++) {
string key = keys[i];
println("key: " + key);
}
}
range
on strings iterates over Unicode code points. The first value is the starting byte index of the rune and the second the rune itself. See [Strings and Runes] for more details.
void main() {
string s = "go";
for (uint i = 0; i < s.length(); i++) {
println(i + " " + s[i]);
}
}
$ asrun range-over-built-in-types.as
sum: 9
index: 1
a -> apple
b -> banana
key: a
key: b
0 103
1 111
Next example: [Pointers]