Dictionaries
A dictionary stores values under keys. Use it when a name such as health is more useful than a position such as item 2.
Create a dictionary
Use braces and give each field a name and a starting value.
player = {
name = 'Ada'
health = 100
}
print(count(player))
2
The dictionary has two entries.
Read a field
Dot syntax is convenient when you know the field name while writing the program.
player = {name = 'Ada', health = 100}
print(player.name)
Ada
The name field contains the text Ada.
Change an existing field
Subtract ten from the recorded health.
player = {health = 100}
player.health -= 10
print(player.health)
90
The update changes the existing entry.
Add a new key
Use brackets when the key comes from a variable.
player = {name = 'Ada'}
field = 'score'
player[field] = 5
print(player.score)
5
Assigning to the missing key creates it.
Remove a key
Pass the dictionary and the key to remove().
player = {name = 'Ada', bonus = 5}
print(remove(player, 'bonus'))
print(count(player))
5
1
remove() returns the deleted value. The name field remains.
Visit keys and values
Give the loop two bindings to read a key and its value together.
player = {name = 'Ada', health = 90}
for key, value in player:
print('{key}: {value}')
name: Ada
health: 90
The dictionary visits the keys in insertion order.
Copy a dictionary
Make a separate top-level dictionary before changing the copy.
player = {health = 90}
saved = copy(player)
saved.health = 100
print(player.health)
90
The original field is unchanged. A shallow copy still shares any nested objects.