- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
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 −
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