Introduction to Functions and Modules edit


Users can extend the language by defining their own modules and functions. This allows grouping portions of script for easy reuse with different values. Well chosen names also help document your script.

OpenSCAD provides:

functions which return values.
modules which perform actions, but do not return values.

OpenSCAD calculates the value of variables at compile-time, not run-time. The last variable assignment within a scope will apply everywhere in that scope. It also applies to any inner scopes, or children, thereof. See Scope of variables for more details. It may be helpful to think of them as override-able constants rather than as variables.

For functions and modules OpenSCAD makes copies of pertinent portions of the script for each use. Each copy has its own scope, which contains fixed values for variables and expressions unique to that instance.

Passing values edit

Functions and modules can receive values to use by several means.

1. The most obvious is via parameters within the parentheses (), which have been declared in the definition. When defined, a parameter can optionally be given a default value. Parameter names are optional in calls if in the order defined, similar to using objects.
2. Variables can be assigned internally
Inside module definitions use: variable = value;
Inside function definitions use: (let variable = value)
3. Variables assigned externally can be seen inside the function or module. These are static, having the value when the function or module was defined.
4. Special variables ($name) assigned externally are more dynamic. They have the values current when and where the call is made.

Functions edit


Functions operate on values to calculate and return new values.

function definition
function name ( parameters ) = value ;
name
Your name for this function. A meaningful name is helpful later.
parameters
Zero or more arguments. Parameters can be assigned default values,to use in case they are omitted in the call. Parameter names are local and do not conflict with external variables of the same name.
value
an expression which calculates a value. This value can be a vector.
function use
When used, functions are treated as values, and do not themselves end with a semi-colon ';'.
 example 1
   
 function func0() = 5;
 function func1(x=3) = 2*x+1;
 function func2() = [1,2,3,4];
 function func3(y=7) = (y==7) ? 5 : 2 ;
 function func4(p0,p1,p2,p3) = [p0,p1,p2,p3];
   
 echo (func0());           // 5
 a =   func1();            // 7
 b=    func1(5);           // 11
 echo (func2());           // [1, 2, 3, 4]
 echo( func3(2),func3());  // 2, 5
  
 z= func4(func0(),func1(),func2(),func3()); //  [5, 7, [1, 2, 3, 4], 5]
  
 translate([0,-4*func0(),0])cube([func0(),2*func0(),func0()]);
 // same as translate([0,-20,0])cube([5,10,5]);
 example 2   creates for() range to give desired no of steps to cover range
 
 function steps( start, no_steps, end) = [start:(end-start)/(no_steps-1):end];
 
 echo( steps(10,3,5));          // [10 : -2.5 : 5]
 for( i=steps(10,3,5))echo(i);  //  10 7.5 5
 
 echo(steps(10,3,15));          //[10 : 2.5 : 15]
 for( i=steps(10,3,15))echo(i); // 10 12.5 15
 
 echo(steps(0,5,5));            // [0 : 1.25 : 5]
 for( i=steps(0,5,5))echo(i);   // 0 1.25 2.5 3.75 5
 
Example 3
 example 3     rectangle with top pushed over, keeping same y
 
 function rhomboid(x=1,y=1,angle=90)
   = [[0,0],[x,0],
     [x+x*cos(angle)/sin(angle),y],
     [x*cos(angle)/sin(angle),y]];
   
 echo (v1); v1 = rhomboid(10,10,35);  // [[0, 0], 
                                      // [10, 0], 
                                      // [24.2815, 10],
                                      // [14.2815, 10]]
 polygon(v1);
 polygon(rhomboid(10,10,35));         // alternate
 performing the same action with a module
  
 module parallelogram(x=1,y=1,angle=90)
   {polygon([[0,0],[x,0],
             [x+x*cos(angle)/sin(angle),y],
             [x*cos(angle)/sin(angle),y]]);};
 
 parallelogram(10,10,35);

Limitations edit

Nested Conditionals edit

Using Let edit

You can also use the let statement:

function get_square_triangle_perimeter(p1, p2) =
  let(hypotenuse=sqrt(p1*p1+p2*p2))
  p1+p2+hypotenuse;

It can be used to store variables in recursive functions.

External Variables edit

Recursive functions edit

Recursive function calls are supported. Using the Conditional Operator "... ? ... : ... ", it is possible to ensure the recursion is terminated.

Note: There is a built-in recursion limit to prevent an application crash. If the limit is hit, the result of the function call is undef.

// recursion - find the sum of the values in a vector (array)
// from the start (or s'th element) to the i'th element - remember elements are zero based

function sumv(v,i,s=0) = (i==s ? v[i] : v[i] + sumv(v,i-1,s));

vec=[ 10, 20, 30, 40 ];
echo("sum vec=", sumv(vec,2,1)); // is 20+30=50