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:
We define a
delayed_value
function that returns a value after a specified delay. This simulates the behavior of channels in the original example.The
select
function takes a list of channel-like functions and returns the first one that’s ready (notundef
).In the
main
function, we set up two “channels” (c1
andc2
) that will return values after 1 and 2 time units respectively.We then use our
select
function twice to simulate waiting for and receiving values from these channels.The results are collected into a list of strings, similar to the print statements in the original example.
To run this code:
- Save it in a file with a
.scad
extension, for exampleselect_simulation.scad
. - Open it in OpenSCAD.
- 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.