Chapter 4. Working with Tables

This chapter explores a new data type called a table. It's a data structure, which means that it lets you combine other values. Because of its flexibility, it is Lua's only data structure. (It is possible to create other, special-purpose data structures in C.)

In this chapter, you learn how to do the following:

  • Create and modify tables

  • Loop through the elements of tables

  • Use Lua's built-in table library

  • Write programs in an object-oriented style

  • Write functions that take variable numbers of arguments

Tables Introduced

The following example creates a table and assigns it to the variable NameToInstr, and then looks around inside the table:

> NameToInstr = {["John"] = "rhythm guitar",
>>   ["Paul"] = "bass guitar",
>>   ["George"] = "lead guitar",
>>   ["Ringo"] = "drumkit"}
> print(NameToInstr["Paul"])
bass guitar
> A = "Ringo"
> print(NameToInstr[A])
drumkit
> print(NameToInstr["Mick"])
nil

A table is a collection of key-value pairs. In this example, the expression that starts and ends with { and } (curly braces) is a table constructor that creates a table that associates the key "John" with the value "rhythm guitar", the key "Paul" with the value "bass guitar", and so on. Each key is surrounded in [ and ] (square brackets) and is separated from its value by an equal sign. The key-value pairs are separated from each other by commas.

After the table is created and assigned to NameToInstr, square brackets are used to retrieve the values for particular keys. When NameToInstr["Paul"] ...

Get Beginning Lua Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.