Easy Tutorial
❮ If Else Statement In Lua Lua Coroutine ❯

Lua Table

A table is a data structure in Lua used to create different data types such as arrays and dictionaries.

Lua tables use associative arrays, where you can use values of any type as array indices, except nil.

Lua tables are dynamically sized; you can expand them as needed.

Lua also uses tables to manage modules, packages, and objects. For example, string.format uses "format" to index the string table.


Table Construction

A constructor is an expression that creates and initializes a table. Tables are a powerful feature unique to Lua. The simplest constructor is {}, which creates an empty table. You can directly initialize an array:

-- Initialize table
mytable = {}

-- Assign values
mytable[1] = "Lua"

-- Remove reference
mytable = nil
-- Lua garbage collection will release the memory

When you set elements for table a and then assign a to b, both a and b point to the same memory. If a is set to nil, b can still access the table elements. If no variables point to a, Lua's garbage collection will clean up the corresponding memory.

Here is an example demonstrating the above scenario:

Example

-- Simple table
mytable = {}
print("Type of mytable is ", type(mytable))

mytable[1] = "Lua"
mytable["wow"] = "Before modification"
print("Element at index 1 is ", mytable[1])
print("Element at index 'wow' is ", mytable["wow"])

-- alternatetable and mytable refer to the same table
alternatetable = mytable

print("Element at index 1 in alternatetable is ", alternatetable[1])
print("Element at index 'wow' in alternatetable is ", alternatetable["wow"])

alternatetable["wow"] = "After modification"

print("Element at index 'wow' in mytable is ", mytable["wow"])

-- Release variable
alternatetable = nil
print("alternatetable is ", alternatetable)

-- mytable is still accessible
print("Element at index 'wow' in mytable is ", mytable["wow"])

mytable = nil
print("mytable is ", mytable)

The output of the above code is:

Type of mytable is     table
Element at index 1 is     Lua
Element at index 'wow' is     Before modification
Element at index 1 in alternatetable is     Lua
Element at index 'wow' in alternatetable is     Before modification
Element at index 'wow' in mytable is     After modification
alternatetable is     nil
Element at index 'wow' in mytable is     After modification
mytable is     nil

Table Operations

Here are some commonly used methods for table operations:

No. Method & Purpose
1 table.concat (table [, sep [, start [, end]]]): Concatenates elements of the specified table from start to end positions, separated by the given separator (sep).
2 table.insert (table, [pos,] value): Inserts a value at the specified position (pos) in the table's array part. If pos is not specified, the value is inserted at the end.
3 table.maxn (table): Returns the largest positive key in the table. If no positive keys are present, it returns 0. (This method is removed in Lua 5.2; a custom function is used here.)
4 table.remove (table [, pos]): Removes and returns the element at the specified position (pos) in the table's array part. Elements following the removed one are shifted forward. If pos is not specified, the last element is removed.
5 table.sort (table [, comp]): Sorts the given table in ascending order.

Let's look at examples of these methods.

Table Concatenation

You can use concat() to output a string concatenated from elements of a list:

Example

fruits = {"banana", "orange", "apple"}
-- Returns concatenated string of table elements
print("Concatenated string ", table.concat(fruits))

-- Specify a separator
print("Concatenated string ", table.concat(fruits, ", "))

-- Concatenate specified indices
print("Concatenated string ", table.concat(fruits, ", ", 2, 3))

The output of the above code is:

Concatenated string     bananaorangeapple
Concatenated string     banana, orange, apple
Concatenated string     orange, apple

Insertion and Removal

The following example demonstrates insertion and removal operations on a table:

Example

fruits = {"banana", "orange", "apple"}

-- Insert at the end
table.insert(fruits, "mango")
print("Element at index 4 is ", fruits[4])

-- Insert at index 2
table.insert(fruits, 2, "grapes")
print("Element at index 2 is ", fruits[2])

print("Last element is ", fruits[5])
table.remove(fruits)
print("Last element after removal is ", fruits[5])

The output of the above code is:

Element at index 4 is     mango
Element at index 2 is     grapes
Last element is     mango
Last element after removal is     nil

Table Sorting

The following example demonstrates the use of sort() to sort a table:

Example

fruits = {"banana", "orange", "apple", "grapes"}
print("Before sorting")
for k, v in ipairs(fruits) do
    print(k, v)
end

table.sort(fruits)
print("After sorting")
for k, v in ipairs(fruits) do
    print(k, v)
end

The output of the above code is:

Before sorting
1    banana
2    orange
3    apple
4    grapes
After sorting
1    apple
2    banana
3    grapes
4    orange

Table Maximum Value

The table.maxn method no longer exists in Lua 5.2. We define the table_maxn function to achieve this.

The following example shows how to get the maximum value in a table:

Example

function table_maxn(t)
  local mn = nil
  for k, v in pairs(t) do
    if mn == nil then
      mn = v
    end
    if mn < v then
      mn = v
    end
  end
  return mn
end
tbl = {[1] = 2, [2] = 6, [3] = 34, [26] = 5}
print("Maximum value in tbl: ", table_maxn(tbl))
print("Length of tbl: ", #tbl)

The output of the above code is:

Maximum value in tbl:     34
Length of tbl:     3

Note:

When obtaining the length of a table using # or table.getn, the count stops at the first gap in indices, potentially leading to an incorrect length.

You can use the following function as an alternative:

function table_leng(t)
  local leng = 0
  for k, v in pairs(t) do
    leng = leng + 1
  end
  return leng
end
❮ If Else Statement In Lua Lua Coroutine ❯