Lua - Accessing Table Fields



Table is the only data structure available in Lua. Table is very flexible in nature. A table can be treated as dictionary, array, hashtables, hashmap, maps and many data structures can be prepared. In this chapter we're discussing the way to access table fields.

Example - Using dot(.) notation

In case of table in form of key-value entries and keys are conforming to variable naming convention, then we can access those fields using dot notation as shown below:

main.lua

-- table with number as key and 6 as value
table = { number = 6}

-- access the field using . notation
print (table.number)

Output

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

6

Example - Using Key-Value Pairs

Let's see another way of defining key-value and accessing them

main.lua

-- table with number as key and 6 as value
table = {["number"] = 6}

-- access the field using . notation
print (table.number)

Output

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

6

Example - Using [](index) notation

Let's see examples of accessing field using [] notation.

main.lua

-- table with number as key and 6 as value
table = { number = 6}

-- access the field using [] notation
print (table["number"])

Output

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

6

Example - Keys within []

Key defined within [] can be accessed using [] as well.

main.lua

-- table with number as key and 6 as value
table = { ["number"] = 6}

-- access the field using [] notation
print (table["number"])

Output

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

6

Output

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

6

Example - Using index notation to numerically indexed table

In case of numerically indexed table, we can access a table fields like an array field with index as shown below−

main.lua

-- numericall indexed table
table = { 6, 7, 8, 9 ,10 }

-- access the field using [] notation
-- array index starts from 1
print (table[1])

Output

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

6
Advertisements