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.
– Gabriel Sales
A doubt, '(%d+)' would be what? Is it a regular expression? And how is one that replaces any value?
– Gabriel Sales
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)– hugomg
Patterns in Lua are similar to regular expressions, but have some differences.
– hugomg
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.?
– Gabriel Sales
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.
– hugomg
Let’s go continue this discussão in chat.
– Gabriel Sales