Lua - Searching Arrays



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 an array 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 - Search Existing Item

Consider the example shown below −

main.lua

-- create an array of fruits
local fruits = { "apple", "orange", "pear", "banana" }

-- set a flag
found = false

-- iterate over fruits
for _, fruit in pairs(fruits) do
   -- if item is present, set flag as true
   if fruit == "pear" then
      found = true
      break
   end
end

-- if found, print success message
if found == true then
   print("Item Found")
else
   print("Item Not Found")
end

Output

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

Item Found

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

Example - Search Non-Existing Item

Consider the example shown below −

main.lua

-- create an array of fruits
local fruits = { "apple", "orange", "pear", "banana" }

-- set a flag
found = false

-- iterate over fruits
for _, fruit in pairs(fruits) do
   -- if item is present, set flag as true
   if fruit == "mango" then
      found = true
      break
   end
end

-- if found, print success message
if found == true then
   print("Item Found")
else
   print("Item Not Found")
end

Output

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

Item Not Found
Advertisements