Callable Values
Lesson 21 of 48 in Coddy's GDScript for JavaScript Developers course.
JavaScript closures retain access to outer bindings, so a later assignment can change the value observed by a callback. GDScript lambda captures of local scalar variables take their value at creation, while captured Arrays and Dictionaries still refer to shared containers. GDScript represents function references as Callable and invokes them with call. Keep a callback distinct from the result of already calling it. A consumer should honor the supplied callable rather than hard-code the behavior of one sample implementation.
Complete JavaScript program files (run main.mjs with Node.js):
JavaScript file main.mjs:
let factor=2;
const scale=n=>n*factor;
factor=3;
console.log(scale(4));JavaScript output:
12Complete GDScript example files:
GDScript file main.gd:
extends Node
func _ready() -> void:
var factor: int = 2
var scale: Callable = func(n: int) -> int: return n * factor
factor = 3
print(scale.call(4))GDScript output:
8Challenge
EasyImplement TransformOps.apply_twice(value:int,operation:Callable)->int by calling the supplied operation twice in succession. Solve uses a doubling callable. The driver also supplies a different callable.
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 transform_ops.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:
if TransformOps.apply_twice(3, func(n: int) -> int: return n + 4) != 11: 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))
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in GDScript for JavaScript Developers
1Scripts and Scalar Values
Run Script FilesText and CommentsBindings and TypesInteger ArithmeticBoolean ResultsRecap: Stock Label2Flow and Functions
Branches and ValuesPattern MatchingLoops and RangesTyped FunctionsDefault ArgumentsRecap: Command CountPractice on your own: Online GDScript compiler