Check values in txt

5

Well, I want to save a value in a txt file, checking if there is already any value with 2 things equal. Ex:

local file = io.open("arquivo.txt", "a+")
local oi = {dia=os.date(), numero=math.random(1,10)}
if not () then -- Aqui não sei o que fazer, quero checar se no txt ja tem alguma linha com o valor numero igual a 'oi.numero', se não tiver, salva.
file:write("Data: "..oi.dia.." - Numero:"..oi.numero)
file:close()
end
    
asked by anonymous 22.08.2014 / 22:08

1 answer

7

To begin with, io.open returns a handle to the file ( you're currently playing it out)

local fil, err = io.open("arquivo.txt", "a+")
if not fil then error(err) end

After that, you can use the lines method to traverse the lines :

for line in fil:lines() do
    -- ...
end

For each line, you will need to do a bit of string manipulation to see if the line contains the number. In your case, the most direct way would be to use the string.match function, which is somewhat similar to regular expressions in other programming languages.

local n = string.match(line, "Numero:(%d+)")
if n and tonumber(n) == oi.numero then
   -- achei o número
end

If you need to analyze the date you can do something like

local date, n = string.match(line, "Data: (.-) Numero:(%d+)")
if date then
    -- o pattern bateu
    fazAlgoCom(date, n)
else
    -- o pattern não bateu
end

The (.-) means "0 or more characters, whichever is the minimum."

However, things start to get more complicated from that point forward. I would prefer to use a more structured storage format, such as CSV, JSON or a "LuaOn" of life (JSON type, but with Lua syntax). It gets more robust (for example, your current version will break if any field has a broken line) and you can use some library ready to handle the job of reading and printing the strings in the right format.

    
22.08.2014 / 22:49