Checking for items in tables Lua
Asked Answered
I

1

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?

Inexpedient answered 30/3, 2017 at 3:23 Comment(0)
B
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!

Berseem answered 30/3, 2017 at 4:13 Comment(2)
I think you mean nil, instead of null, even though this typo has the same effect if you haven't defined null...Descend
You are correct, good spot. I've been writing Java too much lately.Berseem

© 2022 - 2024 — McMap. All rights reserved.