Range Over Built in OpenSCAD

**Range Over Built-in Types in OpenSCAD**

`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.

```openscad
// Summing numbers in a list.
function sum(nums) = 
    let (s = 0) 
    sum_helper(nums, 0);

function sum_helper(nums, idx) = 
    idx == len(nums) ? 0 : nums[idx] + sum_helper(nums, idx + 1);

nums = [2, 3, 4];
sum = sum(nums);
echo("sum:", sum);

Here we use range to sum the numbers in a slice. Arrays work like this too.

range on arrays and slices provides both the index and value for each entry. Sometimes we actually want the indexes.

function find_index(nums, target) = 
    find_index_helper(nums, target, 0);

function find_index_helper(nums, target, idx) = 
    idx == len(nums) ? -1 : (nums[idx] == target ? idx : find_index_helper(nums, target, idx + 1));

target_index = find_index(nums, 3);
echo("index:", target_index);

range on map iterates over key/value pairs.

kvs = [["a", "apple"], ["b", "banana"]];
for (kv = kvs) {
    echo(str(kv[0], " -> ", kv[1]));
}

range can also iterate over just the keys of a map.

for (kv = kvs) {
    echo("key:", kv[0]);
}

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.

txt = "go";
for (i = [0 : len(txt) - 1]) {
    echo(i, : txt[i]);
}

Running this OpenSCAD script will produce the following output in the console:

ECHO: "sum:", 9
ECHO: "index:", 1
ECHO: "a -> apple"
ECHO: "b -> banana"
ECHO: "key: a"
ECHO: "key: b"
ECHO: 0, 103
ECHO: 1, 111

Next example: Pointers.