2

I have a input file with different food types

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

(Don't take these too seriously. I'm no nutrition expert) Anyway, I have the following script that reads the input file then puts the following into a table

    file = io.open("food.txt")
foods = {}
nutritions = {}
for line in file:lines() 
    do
        local f, n, v = line:match("(%a+) (%a+) (%d+)")
        nutritions[n] = {value = v}
        --foods[f] = {} Not sure how to implement here
    end
file:close()

(It's a little messy right now) Notice also that different foods can have different nutrients. For example, eggs have both protein and fat. I need a way to let the program, know which value I am trying to call. For example:

> print(foods.Eggs.Fat)
2
> print(foods.Eggs.Protein
8

I believe I need two tables, as shown above. The foods table will contain a table of nutritions. This way, I can have multiple food types with multiple different nutrient facts. However, I am not sure how to handle a table of tables. How can I implement this within my program?

1 Answer 1

2

The straightforward way is to test if food[f] exists, to decide whether to create a new table or add elements to existing one.

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.