Tables
In Lua, a table is a data type that can be used to store multiple values. Values stored in a table are associated with a “key” — which is used to retrieve the value.
Tables can store any type of value, including numbers, booleans, strings, functions, and more. Any type of data, except nil
can be used as the “key” to associate with a value stored in the table.
Tables are constructed with curly braces{}
. A value stored in a table can be accessed with square brackets []
enclosing the key associated with the value — this is called “indexing” the table.
-- Any value can be stored in a table
local a = {}
a[1] = 'Hello'
a[2] = 'world!'
a[3] = 42
a[4] = true
a[5] = {2, 4, 5} <-- Another table is stored in a[5]
-- The same table can be written as
a = { 'Hello', 'world!', 42, true, {2, 4, 5} }
-- Any data type (except nil) can be used as the key in a table
local b = {}
b['name'] = 'Alex'. <-- The string 'name' is used as the key
b['age'] = 21
b[a] = 'my key is a table!!' <-- The table "a" is used as the key
-- The same table can be written as
b = { name = 'Alex', age = 21, [a] = 'my key is a table!' }
-- Note 1: when using non-sequential or non-numerical keys, the key should be
-- included in this form of writing the table (i.e. name = 'Alex')
-- Note 2: when using a variable as the key, the key must be declared with
-- square brackets. In the above example, 'name' is a string and can be written
-- as (name = 'Alex'). However, 'a' is a variable and so it should be written
-- in square brackets as ([a] = 'my key is a table!')
In the above example, the local variable a
is declared as a an empty table. 5 entries are then assigned to table a
using numbered indexes from 1 to 5, in []
.
Arrays
A table can be used as an array — which is an ordered list of values. When a table is used as an array, the keys have the following three conditions:
- numbered, starting at 1
- sequential
- no gaps between them
The value stored in an array can be any type except nil
(e.g. boolean, number, string, function, custom types, or even another table.)
-- This is an array that contains 3 values
local a = {}
a[1] = 'Hello'
a[2] = 'world!'
a[3] = 42
-- The same array can be written as
local b = { 'Hello', 'world!', 42 }