Advertisement
NanoBob

Computercraft data

Feb 28th, 2016
197
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.68 KB | None | 0 0
  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.     if get(key,name)~=value then
  54.         error("Failed to set value")
  55.     end
  56. end
  57.  
  58. function get(key,name)
  59.     local text=readFile(name)
  60.     local match=string.match(text,"%["..key.."%]=%[.[^%]]*")
  61.     if match==nil then
  62.         return nil
  63.     else
  64.         local final=string.gsub(string.gsub(match,"%["..key.."%]=%[",""),"%]","")
  65.         return final--string.sub(final,1,string.len(final)-1)
  66.     end
  67. end
  68.  
  69. function getAll(name)
  70.     local entries = {}
  71.     local text=readFile(name)
  72.     for entry in string.gmatch(text,"%[.+%]=%[.+%]") do
  73.         entries[#entries+1]=entry
  74.     end
  75.     return entries
  76. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement