Lua Tables

Lua tables are the primary data structure used for organizing and storing data.

They are a versatile data type that can be used for a variety of purposes, including arrays, dictionaries, and objects.

Tables are implemented as associative arrays, which means they are essentially a collection of key-value pairs, where the keys and values can be of any data type.

In this article, we’ll explore what Lua tables are, how they work, and how they can be used to solve real-world programming problems.

Lua Tables – what are they?

Lua tables are associative arrays, also known as maps or dictionaries.

They are a collection of key-value pairs, where each key is unique and maps to a corresponding value. In Lua, keys can be of any data type except for nil, and values can be of any type.

In other programming languages, associative arrays might be implemented as a built-in data type, but in Lua, tables are used for this purpose.

Tables can also be used for other types of data structures, such as arrays, lists, and queues.

Creating Lua Tables

Tables in Lua are represented by curly braces {} with key-value pairs separated by commas.

The key-value pairs can be separated by a colon or an equal sign, and the keys can be either strings or numbers.

To create a new table in Lua, you can use the curly braces {} syntax.

mrxtable = {}

This creates an empty table called mrxtable. You can then add key-value pairs to the table using the following syntax:

mrxtable[1]= "One"

Here a string “One” has been added to the table on the first index. However, you could use any other data type as well.

Removing Reference

A reference from a table is removed using the following syntax:

mrxtable = nil

Garbage Collection

Garbage collection is an automatic operation in Lua that periodically frees up memory no longer used by the program.

When the garbage collector runs and finds a table with no remaining references, it cleans up the memory used by the table. This makes it reusable for other purposes.

In Lua, when we assign a table ‘x’ to another variable ‘y’, both ‘x’ and ‘y’ reference the same memory. This means that no separate memory is allocated for ‘y’; rather, it simply points to the same memory location as ‘x’.

Even if ‘x’ is set to nil, the table will still be accessible to ‘y’, because both variables point to the same memory location. However, when there are no references to the table, it becomes eligible for garbage collection.

The following example demonstrates the operations on a table in Lua:


-- Table initialization _table = {} print("Type of _table is "..type(_table)) print("\n")-- Table Assignment _table[1]= "One" _table[2] = "Two"print("In _table, the element at index 1 is ".. _table[1]) print("In _table, the element at index 2 is ".. _table[2]) print("\n")-- _table and _table2 refer to same table _table2 = _table-- Both _table and _table2 refer to the same memory location print("_table: ",_table) print("_table2: ",_table2) print("\n")print("In _table2, the element at index 1 is ".. _table[1]) print("In _table2, the element at index 2 is ".. _table[2]) print("\n")-- Element at index 2 overwritten in _table2 _table2[2] = "Two in _table2" print("In _table2, the element at index 2 is ".. _table[2]) print("\n")-- only variable released and and not table _table2 = nil print("_table2 is ", _table2) print("\n")-- _table is still accessible print("In _table, the element at index 1 is ".. _table[1]) print("\n")-- Here the key is a string value _table['third'] = "Three" print("In _table, the element at index third is ".. _table["third"]) print("\n")-- _table also assigned to null _table = nil print("_table is ", _table)

Lua Table Methods

In addition to the basic operations in Lua tables we discussed above, Lua provides several built-in methods for manipulating tables.

In this section, we will explore some of the most commonly used Lua table methods.

Lua table.concat(list, [sep [, i [, j]]])

This function concatenates table elements into a string. It takes an optional separator as an argument to separate the elements in the resulting string. The function returns a concatenated string.

The list is the table to be concatenated. It can contain any combination of string and number values.

The sep(optional) is the separator between each element in the concatenated string. By default, the separator is an empty string.

Here i(optional) is the index of the first element to be concatenated. By default, the first element is used.

On the other hand, j(optional) is the index of the last element to be concatenated. By default, the last element is used.

Here is an example for demonstration:


local _table = { "One", "Two", "Three", "Four" }-- concatenate the elements of _table with a comma separator local _result = table.concat(_table, ", ") print(_result)

Lua table.insert(list, [pos,] value)

Used to insert a value into a given list at a specified position.

The list argument is the table into which the value will be inserted, pos is the optional index at which to add the value (defaults to the end of the list) while value is the value to be added.

Let’s take a look at an example:


local _table = {"One", "Two", "Three"}-- insert a value at the end of the table table.insert(_table, "Four")-- insert a value at the beginning of the table table.insert(_table, 1, "Zero")for i, v in ipairs(_table) do print(i-1, v) end

Lua table.remove(list, [pos])

This function is used to remove an element from a table at a given position.

It returns the removed element and shifts all the elements at positions greater than the removed element’s position down by one.

The list parameter is the table from which the element is to be removed.

The pos parameter is the optional position of the element to be removed. If pos is not provided, the last element in the table is discarded.

Below example examines the table.remove() method:


local _table = {"One", "Two", "Three", "Four"}for i, v in ipairs(_table) do print(i, v) end print("\n") -- remove the element at position 2 local removedElement = table.remove(_table, 3) -- print the removed element and the updated table print("Removed element: " .. removedElement) print("\n") for i, v in ipairs(_table) do print(i, v) end

Lua table.sort(list [, comp])

The table.sort(list [, comp]) method in Lua sorts table elements in ascending order. The method can take an optional function comp which defines the order of the elements to be sorted.

The list parameter is the table to be sorted. It can be a list or an associative array. If the list is an associative array, the elements’ indices will not be preserved after sorting.

The optional comp parameter compares two elements in a table. It should return true if the first element is smaller than the second element, false if they are equal, and nil otherwise. If comp is not provided, the default order is the less-than operator (<) for numerical values and the less-than or equal-to operator (<=) for string values.

Following example is used for the illustration of table.sort():


local _table = {"First", "Second", "Third", "Fourth"}-- Sort the table in ascending order of length of the string table.sort(_table, function(a, b) return #a < #b end)-- Print the sorted table for i, value in ipairs(_table) do print(i, value) end

Lua table.pack(…)

This function creates a new table with all the arguments passed to it.

The function returns a table with a n field, which contains the total number of arguments. Additionally, it contains elements indexed from 1 to n.

If n is not explicitly set, it will be set as the argument list length.

Below example is used to demonstrate the table.pack() function:


local new_table = table.pack(1, "Two", 3, "Four") print(new_table.n) -- prints 4 print(new_table[1]) -- prints 1 print(new_table[2]) -- prints "Two" print(new_table[3]) -- prints 3 print(new_table[4]) -- prints "Four"

Lua table.unpack(list [, i [, j]])

The table elements are returned as separate values by this method.

Using starting index i and ending index j, it returns elements between those indices.

Default values for i and j are 1 and the table’s length, respectively.

The following example implements the table.unpack() method in Lua:


local t = {1, 2, 3, 4} print("Result of table.unpack(t):",table.unpack(t)) print("\n") -- Only print elements 2 and 3 of the table print("Result of table.unpack(t, 2, 3):",table.unpack(t, 2, 3))

Lua table.concat(array, separator)

An array-like table can be concatenated into a string using this Lua function.

Here, array is the table containing the elements to concatenate, and separator is an optional string to insert between each element in the final string.

The default separator is an empty string if the separator is not provided.

Let’s explore the table.concat() method through an example:


_table = {"One", "Two", "Three", "Four"} result = table.concat(_table, ", ") print(result)
We value your feedback.

Subscribe To Our Newsletter
Enter your email to receive a weekly round-up of our best posts. Learn more!

Leave a Reply

Your email address will not be published. Required fields are marked *