Dictionary Presence
Lesson 16 of 48 in Coddy's GDScript for Lua Developers course.
Lua uses tables for maps as well as sequences. A missing key reads as nil, and assigning nil removes an entry. False and zero are stored values, so test absence with nil rather than truthiness when false is valid data. GDScript Dictionary can store null as a value; use has when presence itself matters. Its get method supplies a fallback without inserting anything. Direct indexing a missing target key is an error. Mutating either language's map through an alias changes the shared map. The comparison removes a Lua key to expose the difference between absence and a stored target null.
Complete Lua 5.1 comparison. Run main.lua from the directory containing all shown files:
Lua file main.lua:
local d = {free = 0, other = 9}
d.other = nil
print(d.free, d.other == nil)
Lua output:
0 trueGDScript file main.gd:
extends Node
func _ready() -> void:
var d: Dictionary = {"free":0}
print("%d %d" % [d.get("other",9),d.size()])
GDScript output:
9 1Challenge
EasyInputs are a dictionary and key. Return missing when the key is absent; otherwise return the stored integer, including zero.
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 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:
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 Label2Flow and Functions
Branches and ValuesPattern MatchingLoops and RangesTyped FunctionsDefault ArgumentsRecap: Command Count3Collection Ownership
Array OperationsTyped ArraysShared and Copied ArraysDictionary PresenceDictionary TraversalRecap: Word FrequenciesPractice on your own: Online GDScript compiler