Advertisement
theinsekt

FileHelp

Mar 12th, 2015
199
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 2.15 KB | None | 0 0
  1. --get this file: pastebin get QFjF6SMs theinsektAPIs/fileHelp
  2.  
  3. --load contents of a file as a string
  4. function loadString(path)
  5.  local succes=true
  6.  if  not fs.exists(path) then
  7.   return nil
  8.  end
  9.  local h=fs.open(path, "r")
  10.  if h==nil then
  11.   return nil
  12.  end
  13.  local value=h.readAll()
  14.  h.close()
  15.  return value
  16. end
  17.  
  18.  
  19. --save only the given string (value) to a file at the given path
  20. --will clear the previous contents of the file
  21. function saveString(path,value)
  22.  --print("path: "..path)--DEBUG
  23.  --print("value: "..value)--DEBUG
  24.  if type(value)~="string" then
  25.   error("Error: value must be a string")
  26.  end
  27.  --print("opening path: "..path)--DEBUG
  28.  local h = fs.open(path, "w")
  29.  if h==nil then
  30.    return false
  31.  end
  32.  --print("writing value: "..value)--DEBUG
  33.  h.write(value)
  34.  h.close()
  35.  return true
  36. end
  37.  
  38.  
  39.  
  40. --load contents of a file as a string
  41. function loadValue(path)
  42.  local succes=true
  43.  if  not fs.exists(path) then
  44.   return nil
  45.  end
  46.  local h=fs.open(path, "r")
  47.  if h==nil then
  48.   return nil
  49.  end
  50.  local value=h.readAll()
  51.  h.close()
  52.  --unserialize and return data
  53.  local data=textutils.unserialize(value)
  54.  return data
  55. end
  56.  
  57.  
  58. --save only the given string (value) to a file at the given path
  59. --will clear the previous contents of the file
  60. function saveValue(path,value)
  61.  local data=textutils.serialize(value)
  62.  local h = fs.open(path, "w")
  63.  if h==nil then
  64.    return false
  65.  end
  66.  h.write(data)
  67.  h.close()
  68.  return true
  69. end
  70.  
  71.  
  72.  
  73.  
  74.  
  75.  
  76. --load lines from file into a table
  77. function loadLines(path)
  78.  if type(path)~="string" then error("Error (loadLines): path should be a string",2) end
  79.  if  not fs.exists(path) then
  80.   return nil
  81.  end
  82.  local h=fs.open(path, "r")
  83.  if h==nil then
  84.   return nil
  85.  end
  86.  local res={}
  87.  while(true) do
  88.   local line=h.readLine()
  89.   if line==nil then break end
  90.   res[#res+1]=line
  91.  end
  92.  h.close()
  93.  return res
  94. end
  95.  
  96. --splits a string on blank characters (probably)
  97. function splitLine(line)
  98.  if type(line)~="string" then error("Error (getWords): line should be a string",2) end
  99.  local words={}
  100.  --"%S+"
  101.  --"%a+"
  102.  for word in string.gmatch(line, "%S+") do
  103.   words[#words+1]=word
  104.  end
  105.  return words
  106. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement