Channel Buffering in UnrealScript

class ChannelBuffering extends Object;

struct Message
{
    var string Content;
};

var array<Message> Messages;
var int BufferSize;

function Init()
{
    BufferSize = 2;
    Messages.Length = 0;
}

function Send(string Content)
{
    local Message NewMessage;

    if (Messages.Length < BufferSize)
    {
        NewMessage.Content = Content;
        Messages.AddItem(NewMessage);
    }
    else
    {
        `log("Buffer is full. Cannot send message.");
    }
}

function string Receive()
{
    local Message ReceivedMessage;
    local string Content;

    if (Messages.Length > 0)
    {
        ReceivedMessage = Messages[0];
        Content = ReceivedMessage.Content;
        Messages.Remove(0, 1);
        return Content;
    }
    else
    {
        return "";
    }
}

function Example()
{
    Init();

    Send("buffered");
    Send("channel");

    `log(Receive());
    `log(Receive());
}

DefaultProperties
{
}

In UnrealScript, we don’t have built-in channel or buffering mechanisms like in Go. However, we can simulate a similar behavior using an array with a fixed size to represent our buffered channel.

Here’s how the code works:

  1. We define a Message struct to hold our string messages.

  2. We create an array Messages to act as our buffer, and a BufferSize variable to limit its capacity.

  3. The Init() function sets up our buffered channel with a capacity of 2.

  4. The Send() function adds messages to our buffer if there’s space available.

  5. The Receive() function removes and returns messages from the buffer.

  6. The Example() function demonstrates how to use our buffered channel.

To use this code:

  1. Create a new UnrealScript file named ChannelBuffering.uc in your project’s Classes folder.

  2. Copy the above code into the file.

  3. Compile your project.

  4. To run the example, you would typically call the Example() function from another part of your code, such as a game mode or controller.

This implementation mimics the behavior of a buffered channel in Go, allowing you to send up to two messages without immediately receiving them. Keep in mind that UnrealScript doesn’t support true concurrent programming like Go, so this is a simplified simulation of the concept.