5

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?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Reubens4Dinner
  • 343
  • 4
  • 15

1 Answers1

7

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!

ATaco
  • 421
  • 3
  • 11
  • 1
    I think you mean `nil`, instead of `null`, even though this typo has the same effect if you haven't defined `null`... – lhf Mar 30 '17 at 11:55
  • You are correct, good spot. I've been writing Java too much lately. – ATaco Mar 30 '17 at 19:48