Check values in txt

Asked

Viewed 498 times

5

Well, I want to save a value in a txt file, checking if there is already some value with 2 similar things. 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

1 answer

7


For starters, io open. returns a Handle to the file (you are currently throwing it away)

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

After that, you can use the method Lines 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 function string match., 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 any characters, as little as necessary".

However, from this point forward things start to get more complicated. 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). Gets more robust (for example, your current version will break if any field has a line break) and you can use some library ready to handle the work of reading and printing the strings in the right format.

  • Perfect explanation, perfect code. Thank you.

  • A doubt, '(%d+)' would be what? Is it a regular expression? And how is one that replaces any value?

  • 1

    The %d+ means "one or more digits" and the () causes this part of the pattern to be returned by the string.match in case the match works. This is described in the manual section on Patterns. (There is a version of the manual in Portuguese if you want it too)

  • 1

    Patterns in Lua are similar to regular expressions, but have some differences.

  • One more question, and in the case of the "day", this would not be possible because there is more on the right, or has to check up to a character, as a string explodes.?

  • 1

    Returning more than one thing is no problem: functions in Lua can return more than one value (see my Edit). As the split/explode does not have in the standard library, you would need turn around.

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.