Arrays in OpenSCAD

Arrays in OpenSCAD are similar to those in other programming languages, but with some unique characteristics. Let’s explore how to work with arrays in OpenSCAD.

// Here we create an array 'a' that will hold 5 elements.
// In OpenSCAD, arrays are zero-indexed and can hold mixed types.
a = [0, 0, 0, 0, 0];
echo("emp:", a);

// We can set a value at an index using the list comprehension syntax.
a = [for (i = [0:4]) i == 4 ? 100 : 0];
echo("set:", a);
echo("get:", a[4]);

// The len() function returns the length of an array.
echo("len:", len(a));

// Use this syntax to declare and initialize an array in one line.
b = [1, 2, 3, 4, 5];
echo("dcl:", b);

// In OpenSCAD, you can't directly modify arrays, so we create a new one.
b = [1, 2, 3, 4, 5];
echo("dcl:", b);

// OpenSCAD doesn't have a direct equivalent to Go's slice syntax,
// but we can achieve similar results using list comprehension.
b = concat([100], [for (i = [1:2]) 0], [400, 500]);
echo("idx:", b);

// Array types are one-dimensional, but you can
// create multi-dimensional data structures using nested arrays.
twoD = [
    [0, 1, 2],
    [1, 2, 3]
];
echo("2d:", twoD);

// You can also create and initialize multi-dimensional
// arrays at once.
twoD = [
    [1, 2, 3],
    [1, 2, 3]
];
echo("2d:", twoD);

When you run this OpenSCAD script, it will output the following:

ECHO: emp: [0, 0, 0, 0, 0]
ECHO: set: [0, 0, 0, 0, 100]
ECHO: get: 100
ECHO: len: 5
ECHO: dcl: [1, 2, 3, 4, 5]
ECHO: dcl: [1, 2, 3, 4, 5]
ECHO: idx: [100, 0, 0, 400, 500]
ECHO: 2d: [[0, 1, 2], [1, 2, 3]]
ECHO: 2d: [[1, 2, 3], [1, 2, 3]]

Note that arrays in OpenSCAD are immutable, meaning you can’t change individual elements after creation. Instead, you create new arrays with the desired changes. The echo function is used for printing output in OpenSCAD, similar to fmt.Println in the original example.

OpenSCAD’s list comprehension syntax is used to create arrays with specific patterns or to modify existing arrays. This provides similar functionality to the array manipulation shown in the original example.

While OpenSCAD doesn’t have a direct equivalent to some of the array initialization syntaxes shown in the original example (like [...]int{1, 2, 3, 4, 5}), you can achieve similar results using list comprehension or by explicitly listing the elements.