Channel Directions in AngelScript

import std.string;
import std.vector;

// This `ping` function only accepts a channel for sending
// values. It would be a compile-time error to try to
// receive on this channel.
void ping(vector<string>@ pings, const string &in msg) {
    pings.insertLast(msg);
}

// The `pong` function accepts one channel for receives
// (`pings`) and a second for sends (`pongs`).
void pong(vector<string>@ pings, vector<string>@ pongs) {
    if (!pings.isEmpty()) {
        string msg = pings[pings.length() - 1];
        pongs.insertLast(msg);
        pings.removeAt(pings.length() - 1);
    }
}

void main() {
    vector<string> pings;
    vector<string> pongs;
    
    ping(pings, "passed message");
    pong(pings, pongs);
    
    if (!pongs.isEmpty()) {
        print(pongs[pongs.length() - 1] + "\n");
    }
}

In AngelScript, we don’t have built-in channels like in some other languages. Instead, we can simulate this behavior using vectors (dynamic arrays) as a simple form of message passing.

The ping function now takes a vector reference and adds a message to it. The pong function takes two vector references, one for “receiving” (pings) and one for “sending” (pongs). It removes a message from the pings vector and adds it to the pongs vector.

In the main function, we create two vectors to act as our channels. We then call ping and pong as before, and finally print the result.

To run this program:

$ angelscript channel-directions.as
passed message

This example demonstrates how we can implement directional message passing in AngelScript, even though it doesn’t have built-in channel support. The concept of send-only and receive-only channels is simulated through the function signatures and how we interact with the vectors.