Slices in GDScript

extends Node

func _ready():
    # Unlike arrays, arrays in GDScript are dynamic and can hold any type.
    # An uninitialized array is empty and has length 0.
    var s = []
    print("uninit:", s, s == null, s.size() == 0)

    # To create an array with a specific size, we can use the resize() method.
    s.resize(3)
    print("emp:", s, "len:", s.size())

    # We can set and get just like with arrays in other languages.
    s[0] = "a"
    s[1] = "b"
    s[2] = "c"
    print("set:", s)
    print("get:", s[2])

    # size() returns the length of the array as expected.
    print("len:", s.size())

    # GDScript arrays can be extended using the append() method.
    s.append("d")
    s.append_array(["e", "f"])
    print("apd:", s)

    # Arrays can be duplicated using the duplicate() method.
    var c = s.duplicate()
    print("cpy:", c)

    # GDScript supports array slicing with the slice() method.
    var l = s.slice(2, 5)
    print("sl1:", l)

    # This slices up to (but excluding) index 5.
    l = s.slice(0, 5)
    print("sl2:", l)

    # And this slices from index 2 to the end.
    l = s.slice(2, s.size())
    print("sl3:", l)

    # We can declare and initialize an array in a single line as well.
    var t = ["g", "h", "i"]
    print("dcl:", t)

    # GDScript doesn't have a built-in slices package, but we can compare arrays directly.
    var t2 = ["g", "h", "i"]
    if t == t2:
        print("t == t2")

    # Arrays can be nested to create multi-dimensional data structures.
    var twoD = []
    for i in range(3):
        var inner = []
        for j in range(i + 1):
            inner.append(i + j)
        twoD.append(inner)
    print("2d: ", twoD)

# To run this script, attach it to a Node in your Godot scene and run the scene.

GDScript arrays are similar to Go slices in many ways, but there are some differences:

  1. GDScript arrays are dynamic and can hold any type, unlike Go slices which are typed.
  2. GDScript doesn’t have a separate concept of capacity; arrays automatically grow as needed.
  3. Instead of append, GDScript uses append() for single elements and append_array() for multiple elements.
  4. Array slicing in GDScript is done using the slice() method rather than slice notation.
  5. GDScript doesn’t have a separate copy function; instead, use the duplicate() method.
  6. Comparison of arrays in GDScript can be done directly with ==.

The general concepts of working with sequences of data are similar between Go and GDScript, but the syntax and some specific operations differ. This example demonstrates how to perform common slice operations in GDScript, adapting the Go concepts to fit GDScript’s array handling.