Reubens4Dinner
Reubens4Dinner

Reputation: 343

Checking for items in tables Lua

I have an input file

Corn Fiber 17
Beans Protein 12
Milk Protien 15
Butter Fat 201
Eggs Fat 2
Bread Fiber 12
Eggs Cholesterol 4
Eggs Protein 8
Milk Fat 5

This is loaded into a table. I can then run commands to check the value of the items. For example >print(foods.Eggs.Fat) 2

What I need to do is be able to search if an item is already in the table. I have a function that checks if the table has a value, but it doesn't seem to be working. My code:

  file = io.open("food.txt")

    function has_value (tab, val)
    for index, value in ipairs(tab) do
        if value == val then
            return true
        else
            return false
        end
    end
end

    foods = {}
    for line in file:lines() 
        do
            local f, n, v = line:match("(%a+) (%a+) (%d+)")
            if foods[f] then
                foods[f][n] = v
            else
                foods[f] = {[n] = v}
            end
        end
    file:close()

    if has_value(foods, "Eggs") then
        print("Yes")
    else
        print("No")
    end

Even if the table does contain the item, I still am getting false returned from the function. In the example above, if has_value(names, "Eggs") then is printing "No" even when I know Eggs is in the table. Where is my error?

Upvotes: 5

Views: 4500

Answers (1)

ATaco
ATaco

Reputation: 486

You're looking for value in this case, when really you should be looking for key.

function has_key(table, key)
    return table[key]~=nil
end

This function should do what you need it to, and much faster than searching for values, too!

Upvotes: 7

Related Questions