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?
nil
, instead ofnull
, even though this typo has the same effect if you haven't definednull
... – Descend