Nested Tables
A value in a table can be another table, and that one can hold more tables. That's how you describe something bigger, like the whole farm:
local farm = {
name = "Sunflower Farm",
coins = 120,
barn = {eggs = 18, milk = 6},
fields = {"carrot", "potato", "pumpkin"},
}
print(farm.barn.eggs)
print(farm.fields[2])
print(#farm.fields)This prints:
18
potato
3Read farm.barn.eggs from left to right: farm.barn is the barn's table, and .eggs reads the key eggs from it. You can chain dots and square brackets as far as you need: farm.fields[2] is the second item of the list in the field fields. Changing a value works the same way: farm.barn.eggs = farm.barn.eggs + 6.
The inner tables can be dictionaries, lists or records, mixed as you like. Here is a dictionary of records, one for each animal:
local animals = {
bella = {kind = "cow", age = 4},
rex = {kind = "dog", age = 2},
}
print(animals.bella.kind .. ", " .. animals.bella.age .. " years old")
print(animals.rex.kind)cow, 4 years old
dogLists can be nested too: a field of plots, row by row, is a list of lists, and plots[2][3] is the third plot in the second row.
The typical mistake is reading through a table that isn't there. Say Emma keeps her tools in a shed, but the farm has no shed yet:
local farm = {name = "Sunflower Farm", barn = {eggs = 18}}
print(farm.shed.tools)main.lua:3: attempt to index a nil value (field 'shed')To index a table means to get to one of its keys, with a dot or square brackets. farm.shed is nil, and you can't read the key tools from nil. The message names the field that was nil, 'shed': the problem is the part before the last dot, not tools. You get the same error when you assign, farm.shed.tools = 4: Lua doesn't create the inner table for you. Create it first:
local farm = {name = "Sunflower Farm", barn = {eggs = 18}}
farm.shed = {}
farm.shed.tools = 4
print(farm.shed.tools)4Or in one step: farm.shed = {tools = 4}. When you aren't sure that an inner table is there, check first: if farm.shed then … end, or in one expression, farm.shed and farm.shed.tools, which is nil instead of an error when there's no shed.
Instructions
The program ends with an error: the farm itself has no milk; the milk is in the barn. Fix the print so that it prints:
Milk: 6 litersA new hen named Goldie has come to the farm. Below the print, add her to the list farm.animals with table.insert, as a record with the name "Goldie" and the kind "hen". Then go through the list with ipairs and print every animal:
Bella the cow
Rex the dog
Goldie the henEmma has built a shed for her 4 tools. At the end of the program, add the key shed to farm, holding a table with the key tools and the value 4. Then print, reading the number with farm.shed.tools:
Tools: 4Start programming for free
8/10