Slices in OpenSCAD

Our first data structure in OpenSCAD is the list, which is similar to slices in other languages. Lists are an important data type in OpenSCAD, giving a powerful interface to sequences of values.

// Unlike other languages, OpenSCAD doesn't have a dedicated print function.
// We'll use echo() for output, which prints to the console.

// An empty list
s = [];
echo("uninit:", s, len(s) == 0);

// Create a list with initial values
s = ["", "", ""];
echo("emp:", s, "len:", len(s));

// We can set and get just like with arrays
s = ["a", "b", "c"];
echo("set:", s);
echo("get:", s[2]);

// len() returns the length of the list as expected
echo("len:", len(s));

// In OpenSCAD, we use concat() to append elements to a list
s = concat(s, "d");
s = concat(s, ["e", "f"]);
echo("apd:", s);

// To copy a list, we can use the spread operator
c = [...s];
echo("cpy:", c);

// Lists support slicing with the syntax list[start:end]
l = s[2:5];
echo("sl1:", l);

// This slices up to (but excluding) s[5]
l = s[:5];
echo("sl2:", l);

// And this slices up from (and including) s[2]
l = s[2:];
echo("sl3:", l);

// We can declare and initialize a variable for list in a single line
t = ["g", "h", "i"];
echo("dcl:", t);

// OpenSCAD doesn't have a built-in equality function for lists,
// so we'll define our own
function equal_lists(a, b) = 
    len(a) == len(b) && [for(i=[0:len(a)-1]) a[i]==b[i]] == [for(i=[0:len(a)-1]) true];

t2 = ["g", "h", "i"];
if (equal_lists(t, t2)) {
    echo("t == t2");
}

// Lists can be composed into multi-dimensional data structures
twoD = [
    [0],
    [1, 2],
    [2, 3, 4]
];
echo("2d:", twoD);

Note that while lists in OpenSCAD are similar to slices in other languages, they have some key differences:

  1. OpenSCAD lists are immutable. Operations like concat() return new lists rather than modifying existing ones.
  2. OpenSCAD doesn’t have built-in functions for comparing lists or finding elements. You often need to write your own functions for these operations.
  3. OpenSCAD lists are more similar to arrays in other languages, as they don’t have the dynamic resizing capabilities of slices.

To run this code, you would typically save it as a .scad file and open it with the OpenSCAD application. The echo() statements will print their output to the console window in the OpenSCAD interface.

Remember that OpenSCAD is primarily used for creating 3D models, so these list operations are often used in the context of generating or manipulating geometric data.