'Check if table contains number

I need to check if a table contains a specific number that is known.

e.g. My variable is {1, 2, 3, 4, 5} and I want to know how I can check if that variable contains the number 3.

Thanks in advance.



Solution 1:[1]

Just loop over the values of your table and compare them against the number:

function contains(table, number)
    for key, value in pairs(table) do if value == number then return true end end
    return false
end

this will search through the values of both hash & list part. Usage based on your example: var = {1, 2, 3, 4, 5}; assert(contains(var, 3)).

Solution 2:[2]

If your list is sorted, you can use a binary search:

function contains(t, num)
    local upper = #t
    local lower = 1
    while upper >= lower do
        local mid = math.floor((lower + upper) / 2)
        local v = t[mid]
        if v < num then
            lower = mid + 1
        elseif v > num then
            upper = mid - 1
        else -- v == num
            return true
        end
    end
    return false
end

Solution 3:[3]

First off, you need to escape the period as well \.. And since you have some beginning ^ and end of line $ restrictions, you should add those as well.

Since you are streaming the input, you can't undef $/ or it will try to read all 500Gb into memory, and your program will probably just hang. You have to read in line-by-line mode.

You might try a flip-flop operator:

perl -ne'print unless /^COPY/ ... /^\\\.$/' psql.txt

The range operator ... (or ..) will be true if the LHS pattern match is true, and for every line after, until and including when the RHS pattern is true. And false otherwise.

So we print all the lines that are not included in this passage.

Solution 4:[4]

Just use pg_dump with the --schema-only option,

--schema-only Dump only the object definitions (schema), not data. This option is the inverse of --data-only. It is similar to, but for historical reasons not identical to, specifying --section=pre-data --section=post-data.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 LMD
Solution 2 mjmouse
Solution 3
Solution 4 Evan Carroll