Renato D' Oyague
Renato D' Oyague

Reputation: 31

Read in from a file into table of tables

So I have this txt file with elements and the year they were discovered like hydrogen 1766 helium 1868 and many more. I have to read the file and return a table of tables, represeting this information from the file something like this { { "Hydrogen", 1766 }, { "Helium", 1868 }, ... { "Bromine", 1825 }, { "Krypton", 1898 } } but what I have so far its just the name and the year right below it. I have this so far

function read_elements(f_name)
    elements = {}
    f_name = io.open('elements.txt')
    for line in f_name:lines()do
        for word in string.gmatch(line, "%w+") do
            table.insert(elements,word)
        end
    end
    for key,value in pairs(elements) do
        print(value..",")
    end
    f_name:close()
end   

I've been told to hold each pair in their own table and insert those tables into the larger table, but I really don't know what to do next or how to do it. please help

Upvotes: 0

Views: 1040

Answers (1)

William Walsh
William Walsh

Reputation: 96

You are only creating one table, and inserting every found word into it. You need to be creating your main table, then building up an individual table of element and year and inserting that individual table into your main table.

Assuming your file is of the format:

hydrogen 1766 
helium 1868
...

i.e. one element per line, in your first for statement of f_name:lines(), you should be creating a new table, adding each word found (there will be two) to a new table and then adding that to your large table:

function read_elements(f_name)
    local elements = {}
    f_name = io.open('elements.txt')
    for line in f_name:lines()do
        local element = {}
        for word in string.gmatch(line, "%w+") do
            table.insert(element,word)
        end
        table.insert (elements, element)
    end
    f_name:close()
    for _, element in ipairs (elements) do
        for element, year in ipairs (element) do
            print (element, year)
        end
    end
    return (elements)
end 

If your text file is of a different format (possibly just a sequential list, you'll probably want to investigate setting/unsetting a boolean flag every other word on the assumption that each other word is always the year or the element.

Upvotes: 1

Related Questions