Signals in GDScript

Here’s the translation of the Go code to GDScript, formatted in Markdown suitable for Hugo:

Our program demonstrates how to handle signals in GDScript. While GDScript doesn’t have a direct equivalent to Unix signals, we can simulate similar behavior using the OS class and its get_process_id() method.

extends Node

func _ready():
    print("awaiting signal")
    
    # Create a timer to simulate the program running
    var timer = Timer.new()
    timer.connect("timeout", self, "_on_Timer_timeout")
    timer.set_wait_time(5)  # Wait for 5 seconds
    timer.set_one_shot(true)
    add_child(timer)
    timer.start()
    
    # Set up a signal handler
    var pid = OS.get_process_id()
    print("Process ID: ", pid)
    
    # In a real scenario, you would use OS.kill(pid, signal) from another process
    # Here we'll simulate it with a key press
    set_process_input(true)

func _input(event):
    if event is InputEventKey and event.pressed:
        if event.scancode == KEY_C and event.control:
            _handle_signal("SIGINT")
        elif event.scancode == KEY_T and event.control:
            _handle_signal("SIGTERM")

func _handle_signal(sig):
    print()
    print(sig)
    get_tree().quit()

func _on_Timer_timeout():
    print("exiting")
    get_tree().quit()

This script sets up a simple program that waits for a “signal” (simulated by key presses) and handles it accordingly. Here’s how it works:

  1. We use the _ready() function to set up our program. It prints “awaiting signal” and sets up a timer to simulate the program running for a while.

  2. We get the process ID using OS.get_process_id(). In a real scenario, you could use this to send signals to the process.

  3. We set up input processing to simulate receiving signals. Pressing Ctrl+C simulates a SIGINT, and Ctrl+T simulates a SIGTERM.

  4. The _handle_signal() function is called when a “signal” is received. It prints the signal name and quits the program.

  5. If no “signal” is received, the program will exit after 5 seconds when the timer times out.

To run this program, save it as a script attached to a Node in a Godot project. When you run the project, you’ll see:

awaiting signal
Process ID: 12345

Then, if you press Ctrl+C, you’ll see:

SIGINT

And the program will exit. If you don’t press anything, after 5 seconds you’ll see:

exiting

This example demonstrates how to handle “signal-like” events in GDScript, even though it doesn’t have a direct equivalent to Unix signals. The concepts of graceful shutdown and responding to external events are still applicable and important in game development with Godot.