Range Over Built in GDScript

Here we use for to sum the numbers in an array.

extends Node

func _ready():
    var nums = [2, 3, 4]
    var sum = 0
    for num in nums:
        sum += num
    print("sum:", sum)

    for i in range(nums.size()):
        if nums[i] == 3:
            print("index:", i)

    var kvs = {"a": "apple", "b": "banana"}
    for k in kvs.keys():
        var v = kvs[k]
        print("%s -> %s" % [k, v])

    for k in kvs.keys():
        print("key:", k)

    for i in range("go".length()):
        print(i, "go"[i])

Explanation

To run the program, simply put the code into a script in your Godot project and attach it to a Node. The _ready function will automatically run when the scene is ready.

Let’s break down what this script does:

  1. Summing Numbers in an Array:

    var nums = [2, 3, 4]
    var sum = 0
    for num in nums:
        sum += num
    print("sum:", sum)

    This segment creates an array of integers and sums them using a for loop.

  2. Finding Indexes in an Array:

    for i in range(nums.size()):
        if nums[i] == 3:
            print("index:", i)

    This segment demonstrates how to find and print the index of a specific value in the array.

  3. Iterating Over Dictionary Key/Value Pairs:

    var kvs = {"a": "apple", "b": "banana"}
    for k in kvs.keys():
        var v = kvs[k]
        print("%s -> %s" % [k, v])

    Here, we iterate over the key/value pairs in a dictionary and print them.

  4. Iterating Over Dictionary Keys:

    for k in kvs.keys():
        print("key:", k)

    This loop only prints the keys of the dictionary.

  5. Iterating Over Characters in a String:

    for i in range("go".length()):
        print(i, "go"[i])

    Finally, we iterate over each character in a string and print its index and the character.

By running this script within your Godot project, you can observe the various ways to iterate over different data structures and print relevant information. Now that you understand these iterations, you can explore more about the GDScript language and its capabilities.