Signals in AngelScript

Here’s the translation of the Go signals example to AngelScript, formatted in Markdown for Hugo:

Our program will demonstrate how to handle signals in AngelScript. We’ll use a similar concept to channels for communication between different parts of our program.

import std.console;
import std.system;
import std.thread;

// Define our signal types
enum Signal {
    SIGINT,
    SIGTERM
}

// Our signal handler function
void signalHandler(Signal sig, bool &done) {
    console.writeLine();
    console.writeLine(sig == Signal::SIGINT ? "SIGINT" : "SIGTERM");
    done = true;
}

void main() {
    bool done = false;

    // Set up our signal handlers
    system.setSignalHandler(Signal::SIGINT, function(Signal sig) { signalHandler(sig, done); });
    system.setSignalHandler(Signal::SIGTERM, function(Signal sig) { signalHandler(sig, done); });

    // Start a separate thread to simulate the goroutine
    thread signalThread = thread(function() {
        while (!done) {
            thread::sleep(100); // Sleep for a short time to avoid busy waiting
        }
    });

    console.writeLine("awaiting signal");

    // Wait for the signal thread to finish
    signalThread.join();

    console.writeLine("exiting");
}

In this AngelScript version, we use the std.system module to set up signal handlers. We define an enum Signal to represent the different signal types.

The signalHandler function is called when a signal is received. It prints the signal type and sets the done flag to true.

In the main function, we set up the signal handlers using system.setSignalHandler. We then start a separate thread that runs until the done flag is set to true. This thread simulates the goroutine in the original example.

The program waits in the main thread until the signal thread finishes, which happens when a signal is received and processed.

When we run this program, it will block waiting for a signal. By using the appropriate system command to send a SIGINT or SIGTERM signal, the program will print the signal type and then exit.

$ ascript signals.as
awaiting signal
^C
SIGINT
exiting

Note that the exact method to run AngelScript files and send signals may vary depending on your specific AngelScript implementation and operating system.