Variadic Functions in OpenSCAD

Our next program demonstrates variadic functions, which allow a function to accept an arbitrary number of arguments. For instance, fmt.Println is a common example of such a function.

Here’s a function that will take an arbitrary number of int values as arguments.

function sum(nums = []) = 
    let(total = sum_nums(nums))
        [nums, " ", total];

function sum_nums(nums, total = 0) = 
    len(nums) == 0 ? total : sum_nums(nums[1:], total + nums[0]);

// Example usage:

// Variadic function with individual arguments
echo(sum([1, 2]));
echo(sum([1, 2, 3]));

// Applying a list of arguments to the variadic function
nums = [1, 2, 3, 4];
echo(sum(nums));

In this code, the sum function takes an array of integers as an argument. Within the function, the array is iterated to calculate the total sum.

Variadic functions in OpenSCAD are handled by passing a list or array of arguments, as shown. The function sum_nums is used recursively to compute the total sum of the numbers in the array.

To see the output, you can run the code in OpenSCAD and watch the echoed values:

ECHO: [ [1, 2], " ", 3 ]
ECHO: [ [1, 2, 3], " ", 6 ]
ECHO: [ [1, 2, 3, 4], " ", 10 ]

Let’s explore more functionalities of OpenSCAD in the next examples.