Menu
CoddyTech

Signals and Payloads

Lesson 31 of 48 in Coddy's GDScript for PHP Developers course.

PHP event systems commonly store and invoke callables; the language has no Godot signal declaration. GDScript declares a signal, connects Callable listeners and emits payloads. An ordinary nondeferred connection runs during emission, not automatically on a later event loop turn. Listener APIs choose their own delivery rules. Update state before notification when the contract requires it and preserve payload order.

Complete PHP 8.3 program files (run main.php with the CLI):

PHP file main.php:

<?php
declare(strict_types=1);
$seen=[]; $listeners=[function(string $s) use (&$seen): void { $seen[]=$s; }]; foreach($listeners as $listener) $listener("hello"); $listeners=[]; echo $seen[0],"\n";

PHP output:

hello

Complete GDScript example files:

GDScript file demo_notice.gd:

class_name DemoNotice
extends RefCounted
signal message(text: String)

GDScript file main.gd:

extends Node

func _ready() -> void:
	var source: DemoNotice = DemoNotice.new()
	var seen: Array = []
	var callback: Callable = func(text: String) -> void: seen.append(text)
	source.message.connect(callback)
	source.message.emit("hello")
	source.message.disconnect(callback)
	print(seen[0])

GDScript output:

hello
challenge icon

Challenge

Easy

Implement PulseSource with signal changed(value:int), value initially zero and set_value(n:int): emit changed once only when n differs from current value, after updating it. Solve applies inputs and returns final value. Locked probes separately verify event payloads and count.

Input is one JSON array on stdin. The locked main parses it, calls the public APIs and prints result= followed by the returned text and a newline. No helper should print. Independent fixed probes verify required API behavior before the input case; they do not enforce implementation style.

Your code goes in pulse_source.gd, exercise.gd. main.gd holds the supplied input/output code and cannot be edited. Keep each class_name type in its named file.

Try it yourself

extends Node

func contract_ok(data: Array) -> bool:
	var source: PulseSource = PulseSource.new()
	var observed: Array = []
	var record: Callable = func(n: int) -> void: observed.append(n)
	source.changed.connect(record)
	source.set_value(4)
	source.set_value(4)
	source.set_value(2)
	source.changed.disconnect(record)
	if observed != [4,2] or source.value != 2: return false
	return true

func _ready() -> void:
	var data: Array = JSON.parse_string(OS.read_string_from_stdin())
	if not contract_ok(data):
		print("API_CONTRACT_FAILED")
		return
	print("result=" + Exercise.solve(data))
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in GDScript for PHP Developers

Practice on your own: Online GDScript compiler