openscad

OpenSCAD syntax: modify value in vector/list/array


Note: official documentation calls these "vectors", official cheat sheet calls these "lists", and are equivalent in other languages with "arrays". I will refer to them as vectors for now.

I have a vector with values in it, and I'm trying to modify a single vector element. For example I want to to multiply the first element by 2:

vector1 = [10,20,30,40];
vector1[0] = vector1[0] * 2

What is the proper way to do it?

Optional: is there any guide or book where these kind of basics are explained? I'm coming from C/C++, and I'm having a terrible time with script languages like this.


Solution

  • OpenSCAD variables are more like constants than variables in many other languages. Generally, you need to make a new value rather than modify an existing one.

    For lists, you can use a list comprehension:

    vector1 = [10, 20, 30, 40, 50];
    vector2 = [2*vector1[0], each [for (i=[1:len(vector1)-1]) vector1[i]]];
    

    OpenSCAD is a functional programming language. It requires a different mindset than what need for procedural languages like C and C++.