Strings and Runes in OpenSCAD

Our first example demonstrates how to work with strings and characters in OpenSCAD. OpenSCAD doesn’t have built-in string manipulation functions, so we’ll simulate some of the behavior using custom functions.

// Define a string (OpenSCAD doesn't support Unicode, so we'll use ASCII)
s = "Hello";

// Function to get the length of a string
function len(str) = len(str);

// Function to get a character at a specific index
function char_at(str, index) = str[index];

// Function to count characters (simulating rune count)
function char_count(str) = len(str);

// Main logic
echo("Len:", len(s));

// Print each character's ASCII value
for (i = [0:len(s)-1]) {
    echo(str(ord(char_at(s, i)), 16), " ");
}

echo("Character count:", char_count(s));

// Iterate over characters (simulating range loop)
for (i = [0:len(s)-1]) {
    echo(str("U+", str(ord(char_at(s, i)), 16), " '", char_at(s, i), "' starts at ", i));
}

// Function to examine a character (simulating rune examination)
function examine_char(c) =
    c == "H" ? "found H" :
    c == "e" ? "found e" :
    "other character";

// Examine each character
for (i = [0:len(s)-1]) {
    echo(examine_char(char_at(s, i)));
}

In this OpenSCAD code:

  1. We define a string s with the value “Hello”. OpenSCAD doesn’t support Unicode, so we use ASCII characters.

  2. We create custom functions to simulate string operations:

    • len(str) returns the length of a string.
    • char_at(str, index) returns the character at a specific index.
    • char_count(str) simulates counting runes (which is the same as string length for ASCII).
  3. We print the length of the string using echo("Len:", len(s));.

  4. We iterate over each character in the string and print its hexadecimal ASCII value.

  5. We print the character count (which is the same as the string length for ASCII).

  6. We iterate over the characters again, printing each character’s Unicode code point (simulated with ASCII values), the character itself, and its starting position.

  7. We define an examine_char function that checks for specific characters, similar to the rune examination in the original code.

  8. Finally, we iterate over the characters once more, applying the examine_char function to each.

To run this code in OpenSCAD, you would copy it into a .scad file and open it with the OpenSCAD application. The output will appear in the console window.

Note that OpenSCAD’s string handling capabilities are limited compared to general-purpose programming languages. This example demonstrates conceptually similar operations, but the actual functionality and output will differ from the original Go code.