Tables
A table is a Lua data type that can store multiple values including numbers, booleans, strings, functions, and more. Tables are constructed with curly braces ({}
) as shown here:
Once constructed, a table can behave as either an array or a dictionary as illustrated in the following sections.
Arrays
An array is a simple list of ordered values, useful for storing collections of data such as a group of players with special permissions.
Creating Arrays
To create an array using a Lua table, simply store the values sequentially, separated by commas. An array value can be any non-nil
type (boolean, number, string, function, userdata, or even another table).
Reading From Arrays
To read from an array, add a pair of brackets after its reference and specify the index number of the element inside ([pos]
):
Unlike some languages, Lua uses 1-based indexing for arrays, meaning that the first item in the array is [1]
, not [0]
.
Writing Into Arrays
The value of an array index can be defined or rewritten by indicating the index number in brackets ([pos]
) followed by =
and then the value:
Iterating Over Arrays
Arrays can be iterated over (looped through) in two ways:
Use the built-in
ipairs()
function in afor
loop.Get the array’s length using the
#
operator and loop from 1 to that length value.
Inserting Items
An item can be inserted at the end of an array through either of these methods:
Pass the array reference and the item value to Lua’s
table.insert()
function.Add the new item to the array using the
t[#t+1]
syntax.
Last updated