Non Blocking Channel Operations in GDScript

Our first example demonstrates non-blocking channel operations in GDScript. While GDScript doesn’t have built-in channels like Go, we can simulate similar behavior using signals and threads.

extends Node

signal message_received(msg)
signal signal_received(sig)

func _ready():
    # Simulate channels with signals
    var messages = "messages"
    var signals = "signals"

    # Non-blocking receive
    if self.is_connected("message_received", self, "_on_message_received"):
        print("received message")
    else:
        print("no message received")

    # Non-blocking send
    var msg = "hi"
    if self.emit_signal("message_received", msg):
        print("sent message", msg)
    else:
        print("no message sent")

    # Multi-way non-blocking select
    if self.is_connected("message_received", self, "_on_message_received"):
        print("received message")
    elif self.is_connected("signal_received", self, "_on_signal_received"):
        print("received signal")
    else:
        print("no activity")

func _on_message_received(msg):
    print("Received message:", msg)

func _on_signal_received(sig):
    print("Received signal:", sig)

In this GDScript example, we use signals to simulate channel-like behavior. The message_received and signal_received signals act as our channels.

For non-blocking operations:

  1. We use is_connected() to check if a signal has a connected callback, simulating a non-blocking receive.
  2. We use emit_signal() to send a signal, simulating a non-blocking send.
  3. For multi-way select, we use multiple if-elif statements to check different signals.

To run this script:

  1. Create a new GDScript file in your Godot project.
  2. Copy the code into the file.
  3. Attach the script to a Node in your scene.
  4. Run the scene.

The output will depend on whether any signals are connected when the script runs, but it will likely be:

no message received
no message sent
no activity

This example demonstrates how to perform non-blocking operations in GDScript, which can be useful for creating responsive game logic or handling asynchronous events without blocking the main thread.