Tables inside Tables (or nested tables)

In previous lesson we put presidents' personal details into single text string. This could be inconvenient if we may want, say, only years of life of the certain person - we'll need manually extracting it from the text somewhere.

Luckily, we can put tables inside the tables and this allows us modify the code in the following way!

pres = {}
pres['washington'] = {name='George Washington', years='1732-1799', num=1}
pres['lincoln'] = {name='Abraham Lincoln', years='1809-1865', num=16}
pres['roosevelt'] = {name='Theodore Roosevelt', years='1858-1919', num=26}

print(pres['lincoln']['years'])
print(pres['roosevelt'].name)
print(pres.washington.num)

Note there are actually two ways of accessing element by textual key - alternative approach uses dot and doesn't have quotes. This makes it unusable for some advanced cases, but is handy with short and constant keys.

As a sidenote, again, you may suspect that functions like graph.rect, math.sqrt or string.char are really assigned as elements of the corresponding tables (e.g. graph, math and string are variables containing tables of functions) - and that is exactly the case - just convenient way to arrange them!

Exercises

Important thing is that when you insert one table into another, really only reference to this table is inserted, not the whole bulk of data. This allows curious tricks. For example we can make two (or more) tables reference each other, creating circular structure:

a = {value='first', next=nil}    -- "a" points to nowhere with its "next"
b = {value='second', next=a}     -- "b" points to "a" with its "next"
-- put here something to make "a" pointing to "b" with "next" also
print(a.next.value, a.next.next.value, a.next.next.next.value)   -- what you'll see?

For advanced exercise try solving the problem Sort With Indexes where it is convenient to represent the elements to be sorted as small tables themselves (e.g. to keep value and initial index). You'll need to know something about sorting for this, so if you don't, please also solve the "Bubble In Array" and "Bubble Sort" - both are referenced from this problem's statement.