Adding and Removing Keys
A dictionary can change while the program runs. You change a value the same way as a variable, with =. And when you assign to a key that the table doesn't have yet, Lua adds it:
local barn = {carrot = 12, potato = 30}
barn.carrot = barn.carrot + 5
barn.eggs = 18
barn["sweet corn"] = 9
print(barn.carrot, barn.eggs, barn["sweet corn"])This prints:
17 18 9You can also start with an empty table, {}, and add the pairs one by one: local barn = {}, then barn.eggs = 18.
Each key is in a table only once. Assigning to a key that is already there replaces its value; it doesn't add a second pair with the same key.
When you read a key that isn't in the table, it isn't an error: you get nil, as with an index past the end of a list. The error comes only when you try to compute with that nil:
local barn = {carrot = 12, potato = 30}
print(barn.pumpkin)
print(barn.pumpkin + 1)This prints:
nil
main.lua:4: attempt to perform arithmetic on a nil value (field 'pumpkin')The message says field 'pumpkin': in error messages, Lua calls a key of a table a field. A typo ends the same way: barn.carot is nil too, with no warning, because Lua can't know that you meant carrot. Uppercase and lowercase letters matter as well: barn.Carrot is a different key.
When a missing key should count as zero, use or, as for default values in the lesson on conditions: barn.pumpkin or 0 is 0 when there are no pumpkins in the barn, and their number when there are.
To remove a key, assign nil to it: barn.potato = nil. For Lua, a key whose value is nil and a key that isn't in the table are the same thing, so after this line, the potatoes are gone from the table.
And one surprise: # doesn't count the pairs of a dictionary. It counts only the items of a list, the keys 1, 2, 3…:
local barn = {carrot = 12, potato = 30, pumpkin = 4}
print(#barn)0You'll see how to count the keys in the exercise on pairs.
Instructions
The program ends with an error: there are no strawberries in the barn, so barn.strawberry is nil. Emma has just picked 8 baskets of them. Under the comment -- Changes go here:, add the key strawberry with the value 8 to the table (leave the line with the curly braces as it is). The program then prints:
Carrots: 12
Strawberries: 8Emma sells 5 carrots at the market. Below the line that adds the strawberries, decrease the number of carrots in the table by 5. The first line then says:
Carrots: 7Grandpa Joe buys all the potatoes. Below the line that changes the carrots, remove the key potato from the table by assigning nil to it.
At the end of the program, print the potatoes. There are none, so use or 0. Put it in parentheses, (barn.potato or 0): without them, Lua would do the .. first, and the program would end with an error. The new line is:
Potatoes: 0Start programming for free
2/10