
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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
- Related Questions & Answers
- What is the best way to search for an item in a sorted list in JavaScript?
- How to add an item to a list in Kotlin?
- Search for documents matching first item in an array with MongoDB?
- How to search for element in a List in Java?
- How to randomly select an item from a list in Python?
- How to check if an item exists in a C# list collection?
- How to insert an item into a C# list by using an index?
- How to remove an item from a C# list by using an index?
- How to add a list item in HTML?
- How do you check a list contains an item in Java?
- How to insert an item in a list at a given position in C#?
- Set danger action for a list item in a list group with Bootstrap
- Set important information for a list item in a list group with Bootstrap
- Set warning action for a list item in a list group with Bootstrap
- Set success action for a list item in a list group with Bootstrap