Search code examples
arraysluastring-matchingrecursive-querylua-table

Check if Table contains a value in lua


I am looking for a method to see if the value is in array (table)

The example table has 3 entries, each entry containing a table with multiple entries

Say I am checking if 'apple' is in 'data'

  data = {
{"alpha","bravo","charlie","delta"},
{"apple","kiwi","banana","pear"},
{"carrot","brocoli","cabage","potatoe"}
}

This is the code I have, a recursive query. The problem is the function breaks somewhere as it drops the positive value

local function hasValue(tbl, str)

local f = false

    for ind, val in pairs(tbl) do
    
            if type(val) == "table" then
        
                hasValue(val, str)

            else
                    if type(val) == "string" then
         
                        if string.gsub(val, '^%s*(.-)%s*$', '%1') == string.gsub(str, '^%s*(.-)%s*$', '%1') then 
                            f = true
                        end

                    end
            end
    end

return f end

Any help on this or alternative method would be greatly appreciated.

Here is the full test file


Solution

  • local function hasValue( tbl, str )
        local f = false
        for i = 1, #tbl do
            if type( tbl[i] ) == "table" then
                f = hasValue( tbl[i], str )  --  return value from recursion
                if f then break end  --  if it returned true, break out of loop
            elseif tbl[i] == str then
                return true
            end
        end
        return f
    end
    
    print( hasValue( data, 'apple' ) )
    print( hasValue( data, 'dog' ) )
    

    true
    false