Home > Mobile >  Checking if a word is in a array in lua
Checking if a word is in a array in lua

Time:03-11

I'm trying to find a word in the array that has "orange" in it. It works, but when I add the else statement to show the message "matches not found" I get this result.

matches not found
x-orange-test
orange
new_orange
matches not found

What am I doing wrong? Why do I have this message "matches not found" if "orange" exists in the array?

The logic is this: if there is at least one element with the word "orange" in the array, print only those elements. If the array contains no elements with the word "orange" print one line "matches not found" I'm sorry, I'm a newbie to LUA. My code.

local items = { 'apple', 'x-orange-test', 'orange', 'new_orange', 'banana' }
    
    for key,value in pairs(items) do
        if string.match(value, 'orange') then
            print (value)
        else
            print ('matches not found')
        end
    end

the equivalent of the Python code with a slight correction for the summation of the elements found. It works the way I need it to. But I need to figure out how to do the same thing in LUA

#!/usr/bin/env python3
items = ['apple', 'x-orange-test', 'orange', 'new_orange', 'banana']

if any("orange" in s for s in items):
    sum_orange = sum("orange" in s for s in items)
    print (sum_orange)
else:
    print('matches not found')

Thanks in advance.

CodePudding user response:

Your lua code prints the result for every element in the table, so you will get twice the "not found" message because there are indeed two elements without an orange.

Your Python code uses a completely different logic and cannot be compared to the lua code. To fix the lua code you can use something like this:

found = false
for key,value in pairs(items) do
    if string.match(value, 'orange') then
        print (value)
        found = true
    end
end
if not found then
    print ('matches not found')
end

CodePudding user response:

For the first code, you are going through each item in the set and checking if "orange" is contained in the item. And so when you reach am item which does not contain the word "orange", the else condition is true and so matches not found is printed. I would advise you remove the print('matches not found') from the for loop. Rather create a boolean to check if "orange" has found in any of the items in the set. Outside the for loop, you can then check if the boolean is false and then print 'match not found.' See the code below:

local items = { 'apple', 'x-orange-test', 'orange', 'new_orange', 'banana' }
local matchFound = false

    for key,value in pairs(items) do
        if string.match(value, 'orange') then
            print (value)
            matchFound = true
        end
    end

    if not matchFound then
        print('matches not found')
  • Related