Creating Lists in Lua

Lists, often also called arrays, are data structures that organize elements such as values by index.

A list is created by instantiating a table of values, as below:

-- initialize a table with values

local x = { "a", "b", "c" }

Let's try printing the list:

print(x) -- table: 0x6121ee19eda0

By default, when Lua prints a table it displays the type (table) followed by its address in memory, which can be useful in some situations but generally isn't what we want. Inspecting the values of a list requires accessing them individually.

-- access values stored in the table

print(x[1]) -- a
print(x[2]) -- b
print(x[3]) -- c

-- accessing values *not* in the table returns nil

print(x[9]) -- nil

There is a second method for creating lists, which is often helpful when creating lists programmatically such as in a loop. In this this method, an empty list is created and assigned to a variable, then values are assigned directly by index:

-- initialize an empty table

local x = {}

-- assign values by index

x[1] = "d"
x[2] = "e"
x[3] = "f"

After the list is created, its elements can be accessed as usual:

-- access values stored in the table

print(x[1]) -- d
print(x[2]) -- e
print(x[3]) -- f

A variation on this method uses the table.insert method to append values to the list, and will be discussed shortly.