Lua - Table Searching



When we want to iterate over an item to find a specific value we usually make use of the for loop. It's always the most intuitive approach and it is a recommended one.

Let’s explore an example where we have a table of fruits stored in Lua, and then we want to check if a particular fruit is present in it or not. For that, the most native and yet efficient approach would be to just iterate over the table elements and compare each element with the element we are looking for. This technique or approach is also known as linear search.

Example - Searching element in a Table

Consider the example shown below −

main.lua

local fruits = { "apple", "orange", "pear", "banana" }
for _, fruit in pairs(fruits) 
do
   if fruit == "pear" then
   do 
	  print("We Found it!")
      break
   end
      else print("Oh no, keep traversing!")
   end
end

Output

When we run the above code, we will get the following output−

Oh no, keep traversing!
Oh no, keep traversing!
We Found it!

While the above approach works perfectly fine, it is recommended to make use of a set instead of traversing the table.

Example - Using Set to search element

The following example uses the Set approach that we can make use of and it works like a charm. Consider the example shown below −

main.lua

function Set (table)
   local set = {}
   for _, l in ipairs(table)
   do
      set[l] = true
   end
   return set
end

local fruits = Set { "apple", "orange", "pear", "banana" }

   if fruits["pear"] then
   do
      print("Present in the set")
   end
end

Output

When we run the above code, we will get the following output−

Present in the set
Advertisements