Hey guys, I'm relatively new to saving data in gmod lua and I was wondering what the best way would be to check if a line exists, if it does insert code on the line above, or below it, if it doesn't exist, insert code at the end of the file. Hopefully that made sense.
Well, this is more a question about strings than file contents, but here's what I'd do:
First, read the file using [img]http://wiki.garrysmod.com/favicon.ico[/img] [url=http://wiki.garrysmod.com/page/file/Read]file.Read[/url], then separate it up by newlines using [img]http://wiki.garrysmod.com/favicon.ico[/img] [url=http://wiki.garrysmod.com/page/string/Explode]string.Explode[/url].
Then, I'd check through each of the lines in the table given by that function to see if the line you want exists.
If it does, I'd then insert it into the table wherever you want it and [img]http://wiki.garrysmod.com/favicon.ico[/img] [url=http://wiki.garrysmod.com/page/string/Implode]string.Implode[/url] it back into a string, then [img]http://wiki.garrysmod.com/favicon.ico[/img] [url=http://wiki.garrysmod.com/page/file/Write]file.Write[/url] that string to the original file. If it doesn't exist, I'd use [img]http://wiki.garrysmod.com/favicon.ico[/img] [url=http://wiki.garrysmod.com/page/file/Append]file.Append[/url] to add it onto the end.
[editline]4th July 2016[/editline]
Another thing you could try could be to use [img]http://wiki.garrysmod.com/favicon.ico[/img] [url=http://wiki.garrysmod.com/page/file/Open]file.Open[/url], which would then let you use [img]http://wiki.garrysmod.com/favicon.ico[/img] [url=http://wiki.garrysmod.com/page/File/ReadLine]File:ReadLine[/url].
[editline]4th July 2016[/editline]
Sorry for such a long explanation, but what you're trying to do is a bit tricky to do
Warning: Pattern wizardry ahead
[CODE]
local beforetext = "text above the line"
local aftertext = "text after the line"
local textmatch = "the line to find (not includeing \n)"
local filepath = "/path/to/the/file.txt"
local filetxt = file.Read(filepath,"DATA")
local nstr, found= filetxt:gsub("(.*\n?)("..textmatch..")(.*\n?)","%1"..beforetext.."\n%2\n"..aftertext.."%3")
if found == 0 then
file.Append(filepath,"\n"..textmatch)
else
file.Write(filepath,nstr)
end
[/CODE]
See [URL="http://lua-users.org/wiki/PatternsTutorial"]the lua pattern tutorial[/URL] and [URL="http://www.lua.org/pil/20.3.html"]the lua manual section on captures[/URL] for more than you ever wanted to know about string matching.
Sorry, you need to Log In to post a reply to this thread.