Lua - Table Constructors
Table is a versatile data structure in Lua and is used to create various types like array/dictionary or to create various data structures like stack, queue, linked list etc. A table can be in numerically indexed form or in a key-value pairs based associated form.
A table can be contructed in multiple ways. We'll cover most of the ways how to initialize a table in examples below−
Example - Using empty constructor
A table can be initialized as an empty table and then entries can be added later as required as shown below−
main.lua
-- empty table initialization using default constructor
numbers = {}
numbers[1] = 11
numbers[2] = 22
numbers[3] = 33
for k,v in pairs(numbers) do
print(k, v)
end
Output
When the above code is built and executed, it produces the following result −
1 11 2 22 3 33
Example - Initialize associative table at time of creation
A assoicative table can be initialized at the time of creation as required as shown below−
main.lua
-- initialize table of fruits
fruits = {[2] = "banana",[4] = "orange",[6]="apple",[8] = "grapes"}
-- print the entries of table along with keys
for key,value in pairs(fruits) do
print(key,value)
end
Output
When the above code is built and executed, it produces the following result −
8 grapes 2 banana 4 orange 6 apple
Example - Initialize numerically indexed table at time of creation
We can define a table without specifying the indexes as shown below−
main.lua
-- initialize table of numbers
numbers = {11, 22, 33, 44, 55, 66}
-- print the entries of table along with keys
for key,value in ipairs(numbers) do
print(key,value)
end
Output
When the above code is built and executed, it produces the following result −
1 11 2 22 3 33 4 44 5 55 6 66
Example - Create Associative as well as numeric table
Following is an example where we've specified key-value as well as a numeric indexed array.
main.lua
-- initialize table of numbers
numbers = {[7] = 11, 22, 33, 44, 55, 66}
-- print the entries of table along with keys
for key,value in pairs(numbers) do
print(key,value)
end
Output
When we run the above program, we will get the following output−
1 22 2 33 3 44 4 55 5 66 7 11
Example - Create Merged table
Following is an example where we've two tables separated by ;.
main.lua
-- initialize table of numbers
numbers = {[7] = 11; 22, 33, 44, 55, 66}
-- print the entries of table along with keys
for key,value in pairs(numbers) do
print(key,value)
end
Output
When we run the above program, we will get the following output−
1 22 2 33 3 44 4 55 5 66 7 11