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.
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.
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
.
Lua tables are heterogeneous in nature. That is, they can contain the value of any data type except nil
.
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]
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'}
tableVal = {} --> Create a tableleon = "light"tableVal[leon] = 1000; --> The leon value "light" turns to the key of the new table entryprint( tableVal[leon] ) --> Access the value with the key variable "leon"print( tableVal["light"] ) --> Access the value with the key "light" itselfprint( tableVal.light ) --> Another way to access the value with the "light" keytableVal[3] = "child" --> Make a new table entry with key = 3 and value = "child"print( tableVal[3] ) --> Access and display this new entrylua = {'image','name','school'} --> Create a new table with the valueprint(lua[2])
leon
."light"
."light"
key. This is the dot convention.3
.2
of the new table.