What is a table in Lua?

Overview

The Lua programming language has many data types, including numbers, strings, nil, boolean, functions, and tables.

The table data structure provides us the facility to create arrays.

Tables in Lua

When we have to create custom structures like dictionaries and arrays in Lua, we use the table data type.

Table values are more like objects. The reference to the table object, rather than its copy, is manipulated when it is passed, assigned, or returned.

Note: The first index of tables in Lua is 1, unlike the arrays in other languages.

Forms of tables

Tables in Lua can be in the form of associative arrays. Other than the normal number indexing of its element, a table value can be indexed with keys of any data type except nil.

Nature of tables

Lua tables are heterogeneous in nature. That is, they can contain the value of any data type except nil.

Accessing table elements

Let’s suppose we have a table:

tab = {3,7,10}

If we want to access any value from the table, we can write the following:

tab[7]

Constructing tables

To construct a table, we have to give it an identifier and equate it to a curly bracket, inside which we add the table values.

Below is an example of how we can create a table in Lua.

luaTable = {}

The example above is of a simple table, although it has no value. Below is a table with values added.

lua = {'image','name','school'}

Example

tableVal = {} --> Create a table
leon = "light"
tableVal[leon] = 1000; --> The leon value "light" turns to the key of the new table entry
print( tableVal[leon] ) --> Access the value with the key variable "leon"
print( tableVal["light"] ) --> Access the value with the key "light" itself
print( tableVal.light ) --> Another way to access the value with the "light" key
tableVal[3] = "child" --> Make a new table entry with key = 3 and value = "child"
print( tableVal[3] ) --> Access and display this new entry
lua = {'image','name','school'} --> Create a new table with the value
print(lua[2])

Explanation

  • Line 1: We create a table.
  • Line 3: We declare a string value.
  • Line 4: We used the declared string as the key to a new entry into the table.
  • Line 6: We access the newly added value with the key’s variable name, leon.
  • Line 7: We access the newly added value with the key’s "light".
  • Line 8: We use another way to access the value with the "light" key. This is the dot convention.
  • Line 10: We add a new value to the table with the index key 3.
  • Line 12: We display the newly added value.
  • Line 14: We create another table.
  • Line 15: We display the value at index 2 of the new table.