Sets and Membership
Lesson 24 of 48 in Coddy's Lua for GDScript Developers course.
GDScript developers often represent a collection of unique labels with dictionary keys and test membership using has. The same representation works in Lua: store true at every member key. Assigning the same key again leaves one entry, which removes duplicates naturally. Lua has no dedicated set type or dictionary membership method. Test a key with seen[label] ~= nil when presence matters. Removing a member means assigning nil. This differs from assigning false, which leaves the key present. An explicit count through pairs gives the number of distinct labels, including the empty string if it is a valid label.
GDScript 4
extends SceneTree
func _init():
var seen = {}
for label in ["north", "north", "south"]:
seen[label] = true
seen["east"] = false
print(str(seen.size()) + ":" + ("present" if seen.has("east") else "missing"))
quit()Lua 5.1
local seen = {}
for _, label in ipairs({"north", "north", "south"}) do
seen[label] = true
end
seen.east = false
local count = 0
for _ in pairs(seen) do count = count + 1 end
print(count .. ":" .. (seen.east ~= nil and "present" or "missing"))Porting trap
A GDScript has check asks whether a key exists, not whether its value is true. Preserve that distinction with ~= nil when porting.
Challenge
EasyInput lines are labels. Return the number of distinct labels. Repeated labels count once; empty input returns zero.
Edit app.lua. The visible locked main.lua reads stdin into a sequence of lines, calls app.run(lines), and prints its returned value with one final newline. Do not print diagnostics or change the module names. Empty input gives an empty sequence. All numeric inputs are small enough to avoid overflow.
Try it yourself
local app = require("app")
local lines = {}
for line in io.lines() do lines[#lines + 1] = line end
print(app.run(lines))
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Lua for GDScript Developers
1First Lua Programs
Run Lua ModulesPrint and CommentNames and Local ScopeNumbers and ConversionStrings and Byte IndexesRecap: Format a Receipt4Functions and Closures
Functions and ReturnsDefaults and Missing ValuesMultiple Results and VarargsCallbacks and Captured StateRecap: Pricing Functions2Values and Decisions
null and Missing FieldsTruth and Default ValuesBranches and BoundsEquality and IdentityRecap: Admission Rules5Tables as Collections
Arrays as Dense TablesDictionaries and pairsSets and MembershipAliasing and Shallow CopiesRecap: Count InventoryPractice on your own: Online Lua compiler