Channel Directions in GDScript

extends Node

# This `ping` function only accepts a string parameter and sends it to a queue.
# GDScript doesn't have built-in channels, so we'll use a queue to simulate this behavior.
func ping(queue: Array, msg: String) -> void:
    queue.append(msg)

# The `pong` function accepts two queues, one for receiving and one for sending.
func pong(pings: Array, pongs: Array) -> void:
    var msg = pings.pop_front()
    pongs.append(msg)

func _ready():
    var pings = []
    var pongs = []
    ping(pings, "passed message")
    pong(pings, pongs)
    print(pongs.pop_front())

In GDScript, we don’t have built-in channels like in some other languages. Instead, we can use Arrays as queues to simulate similar behavior. The concept of channel directions is replaced by using separate arrays for “sending” and “receiving”.

The ping function takes an array (acting as a queue) and a message. It appends the message to the queue, simulating sending a value to a channel.

The pong function takes two arrays: pings for receiving and pongs for sending. It removes the first item from the pings array (simulating receiving) and appends it to the pongs array (simulating sending).

In the _ready function (which is the entry point in GDScript, similar to main), we create two arrays to act as our queues. We then call ping and pong, and finally print the result.

To run this script:

  1. Save it as a .gd file in your Godot project.
  2. Attach it to a Node in your scene.
  3. Run the scene.

The output will be:

passed message

This example demonstrates how to simulate channel-like behavior in GDScript, even though the language doesn’t have built-in channels. It showcases the flexibility of GDScript in adapting concepts from other languages.