SHOW:
|
|
- or go back to the newest paste.
| 1 | local fileName="db/test" | |
| 2 | ||
| 3 | function readFile(name) | |
| 4 | local filename=name | |
| 5 | if filename==nil then | |
| 6 | filename=fileName | |
| 7 | end | |
| 8 | if fs.exists(filename)==false then | |
| 9 | fs.open(filename,"w").close() | |
| 10 | end | |
| 11 | local file=fs.open(filename,"r") | |
| 12 | local text=file.readAll() | |
| 13 | file.close() | |
| 14 | return text | |
| 15 | end | |
| 16 | ||
| 17 | function cleanFile(name) | |
| 18 | local text=readFile(name) | |
| 19 | repeat | |
| 20 | text=string.gsub(text,"%]%]","]") | |
| 21 | until string.match(text,"%]%]")==nil | |
| 22 | writeFile(name,text,true) | |
| 23 | end | |
| 24 | ||
| 25 | function writeFile(name,text,isCleaning) | |
| 26 | local filename=name | |
| 27 | if filename==nil then | |
| 28 | filename=fileName | |
| 29 | end | |
| 30 | fs.delete(filename) | |
| 31 | local file=fs.open(filename,"w") | |
| 32 | file.write(text) | |
| 33 | file.close() | |
| 34 | if isCleaning==nil then | |
| 35 | cleanFile(name) | |
| 36 | end | |
| 37 | end | |
| 38 | ||
| 39 | function set(key,value,name) | |
| 40 | local text=readFile(name) | |
| 41 | local currentValue=get(key,name) | |
| 42 | if currentValue==nil then | |
| 43 | if value==nil then | |
| 44 | return | |
| 45 | end | |
| 46 | writeFile(name,text.."\n["..key.."]=["..tostring(value).."]") | |
| 47 | else | |
| 48 | if value==nil then | |
| 49 | writeFile(name,text:gsub("%["..key.."%]=%[.[^%]]*",""))
| |
| 50 | end | |
| 51 | writeFile(name,text:gsub("%["..key.."%]=%[.[^%]]*","["..key.."]=["..tostring(value)..""))
| |
| 52 | end | |
| 53 | end | |
| 54 | ||
| 55 | function get(key,name) | |
| 56 | local text=readFile(name) | |
| 57 | local match=string.match(text,"%["..key.."%]=%[.[^%]]*") | |
| 58 | if match==nil then | |
| 59 | return nil | |
| 60 | else | |
| 61 | local final=string.gsub(string.gsub(match,"%["..key.."%]=%[",""),"%]","") | |
| 62 | return final--string.sub(final,1,string.len(final)-1) | |
| 63 | end | |
| 64 | end | |
| 65 | ||
| 66 | function getAll(name) | |
| 67 | local entries = {}
| |
| 68 | local text=readFile(name) | |
| 69 | for entry in string.gmatch(text,"[^%[.]+%]=%[[^%]]+") do | |
| 70 | local start = string.find(entry,"%]=%[") | |
| 71 | local id = string.sub(entry,0,start-1) | |
| 72 | local value = string.sub(entry,start+3,string.len(entry)) | |
| 73 | entries[id]=value | |
| 74 | end | |
| 75 | return entries | |
| 76 | end |