Lua - Nested Tables



Nested Table is a very important concept which can help in storing the structured data in a data-struture. Consider following scenarios−

  • Table of Student Details having student and address as a nested tables.

    studentDetails = {
    	student = { name = "Robert", age = "12"},
    	address = { city = "HYD", pincode = "500031"}
    }
    
  • Table of Game with details of player and scores as a nested tables.

    playerDetails = {
    	player = { name = "Robert", level = "12"},
    	scores = { 23, 33, 77, 94, 78}
    }
    
  • and so on..

Accessing nested Table fields

A nested field of a table can be accessed in two ways.

  • Using array like, [] notation.

  • Using . notation.

Example - Using array notation to access nested field with text based key.

Consider the following example, where we're accessing a student name using array notation as text based key.

main.lua

-- define a nested structure
studentDetails = {
	student = { name = "Robert", age = "12"},
	address = { city = "HYD", pincode = "500031"}
}

-- access student name
name = studentDetails["student"]["name"]

-- print student name
print(name)

Output

When the above code is built and executed, it produces the following result −

Robert

Example - Using array notation to access nested field with index based key.

Consider another example, where we're accessing a student details using array notation as number based key.

main.lua

-- define a nested structure
students = {
	[1] = { name = "Robert", rollNo = "1"},
	[2] = { name = "Julie", rollNo = "2"},
	[3] = { name = "Adam", rollNo = "3"},
}

-- access student name
name = students[2]["name"]

-- print student name
print(name)

Output

When the above code is built and executed, it produces the following result −

Julie

Example - Navigating through nested Table

We can access a nested array easily and can navigate through it. See the example below:

main.lua

-- define a nested structure
playerDetails = {
	player = { name = "Robert", level = "12"},
	scores = { 23, 33, 77, 94, 78}
}

-- access player name
name = playerDetails["player"][name"]

-- print player name
print(name)

-- access player scores
scores = playerDetails["scores"]

-- print player scores
for index, score in ipairs(scores) do
   print(index, score)
end

Output

When the above code is built and executed, it produces the following result −

Robert
1	23
2	33
3	77
4	94
5	78
Advertisements