Failure as Data
Lesson 33 of 48 in Coddy's GDScript for Lua Developers course.
Lua pcall invokes a function in protected mode and returns a success flag plus results or an error value. Protection does not roll back mutations already made. GDScript has no equivalent general try-catch mechanism for script runtime errors. Expected domain rejection should be returned as a status, null or a documented result structure. Validate before mutation when a failed operation must preserve state. A target runtime error or push_error produces diagnostics rather than a normal rejection value; this runner rejects stderr even if the process exit is zero. The comparison catches a deliberate Lua failure without writing stderr.
Complete Lua 5.1 comparison. Run main.lua from the directory containing all shown files:
Lua file main.lua:
local ok, value = pcall(function() error("rejected", 0) end)
print(ok)
print(value)
Lua output:
false
rejectedGDScript file main.gd:
extends Node
func _ready() -> void:
var result: Dictionary = {"ok":false,"value":3}
print("accepted" if result["ok"] else "rejected")
GDScript output:
rejectedChallenge
EasyImplement CreditBox with balance initially 5 and spend(n:int)->bool. Reject negative or unaffordable spending without changing balance. Otherwise subtract and return true. The solve function returns success:balance using lowercase true or false.
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 credit_box.gd, exercise.gd. The supplied main.gd cannot be edited. Keep each class_name type in its named file.
Try it yourself
extends Node
func contract_ok(data: Array) -> bool:
var box: CreditBox = CreditBox.new()
if box.spend(-1) or box.spend(6) or box.balance != 5: return false
if not box.spend(2) or box.balance != 3 or not box.spend(0): 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 Lua Developers
1Scripts and Scalar Values
Run Script FilesText and CommentsBindings and TypesInteger ArithmeticBoolean ResultsRecap: Stock Label7Events and Failure
Connection LifetimesFailure as DataValidated ConversionRecap: Safe DivisionScript Loading2Flow and Functions
Branches and ValuesPattern MatchingLoops and RangesTyped FunctionsDefault ArgumentsRecap: Command CountPractice on your own: Online GDScript compiler