Select in OpenSCAD

OpenSCAD doesn’t have built-in support for concurrency or channels, so we’ll simulate the behavior using functions and a custom implementation of a select-like mechanism.

Our example will demonstrate a similar concept using functions that return after a delay:

// Simulate a channel-like behavior
function delayed_value(delay, value) =
    let(start = $t)
    $t >= start + delay ? value : undef;

// Simulate select behavior
function select(channels) =
    let(
        values = [for (c = channels) c()],
        ready_indices = [for (i = [0:len(values)-1]) if (values[i] != undef) i],
        chosen_index = ready_indices[0]
    )
    chosen_index != undef ? [chosen_index, values[chosen_index]] : undef;

// Main function to demonstrate select-like behavior
function main() =
    let(
        c1 = function() delayed_value(1, "one"),
        c2 = function() delayed_value(2, "two"),
        channels = [c1, c2],
        result1 = select(channels),
        result2 = select(channels)
    )
    [
        if (result1 != undef) str("received ", result1[1]),
        if (result2 != undef) str("received ", result2[1])
    ];

// Execute the main function
echo(main());

This code simulates the behavior of the original example:

  1. We define a delayed_value function that returns a value after a specified delay. This simulates the behavior of channels in the original example.

  2. The select function takes a list of channel-like functions and returns the first one that’s ready (not undef).

  3. In the main function, we set up two “channels” (c1 and c2) that will return values after 1 and 2 time units respectively.

  4. We then use our select function twice to simulate waiting for and receiving values from these channels.

  5. The results are collected into a list of strings, similar to the print statements in the original example.

To run this code:

  1. Save it in a file with a .scad extension, for example select_simulation.scad.
  2. Open it in OpenSCAD.
  3. Look at the console output to see the results.

The output should look something like this:

ECHO: ["received one", "received two"]

Note that OpenSCAD doesn’t have real-time capabilities or true concurrency, so this is a simplified simulation of the select behavior. The timing in OpenSCAD is controlled by the $t variable, which you can adjust in the OpenSCAD interface.

This example demonstrates how we can simulate channel-like behavior and a select mechanism in OpenSCAD, even though it doesn’t have built-in support for these concepts.