What is a Set?
Part of the Logic & Flow section of Coddy's GDScript journey. Lesson 31 of 78.
A set is a collection of unique values: each value is in it once or not at all. The question you ask a set is "is this value a member?". The badges a player has earned, the levels already visited and the usernames already taken are sets.
An array keeps every copy you add:
var pickups := ["sword", "shield", "sword"]
print(pickups.size()) # 3GDScript has no Set type. Instead, you use a dictionary: its keys are unique, so the keys are the members of the set. The values are not used, and by convention every value is true:
var items := {"sword": true, "shield": true}
items["sword"] = true # already a member: nothing changes
print(items.size()) # 2
print(items.keys()) # ["sword", "shield"]keys() returns the members as an array, in the order they were first added. An empty set is an empty dictionary, {}.
A set literal lists each member once. Writing the same key twice inside {} is an error that stops the program before it runs.
To make the set's type explicit, use a typed dictionary: var badges: Dictionary[String, bool] = {}
Challenge
EasyA player played four matches and earned one badge in each. Some badges repeat. The program reads four lines of input, one badge name per line.
Add each badge to the set badges, then print the number of different badges and the members of the set as an array. For the badges Sniper, Medic, Sniper and Builder, the output is:
Unique badges: 3
["Sniper", "Medic", "Builder"]Try it yourself
extends Node
func _ready():
var badges := {}
for i in range(4):
var badge := OS.read_string_from_stdin()
# Add the badge to the set
pass
# Print the number of badges and the badges
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
String MethodsSearching in StringsReplace and TrimSplit and JoinRecap - Username Check4Dictionaries Part 2
Nested DictionariesArrays of DictionariesMerging DictionariesCopying DictionariesRecap - Frequency Counter2Advanced Decision Making
Match With VariablesMatch GuardsArray PatternsDictionary PatternsMembership ChecksRecap - Command Parser5Contact Book Application
Display MenuAdd Contact8Student Records Manager
Project OverviewAdd Student3Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysJagged ArraysCommon 2D Array PatternsRecap - Game Board6Sets with Dictionaries
What is a Set?Dictionary as a SetAdding and RemovingUnion and IntersectionSet DifferenceRecap - Remove Duplicates9Advanced Data Aggregation
Summing ValuesFinding Minimum and MaximumCustom SortingRecap - Dictionary SorterPractice on your own: Online GDScript compiler