How to search for an item in a Lua List?


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 list 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 list elements and compare each element with the element we are looking for. This technique or approach is also known as linear search.

Example

Consider the example shown below −

 Live Demo

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

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 list.

Example

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

 Live Demo

function Set (list)
   local set = {}
   for _, l in ipairs(list) 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

Present in the set

Updated on: 20-Jul-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements