Advertisement
PaymentOption

Table saver and reader

Sep 29th, 2012
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.43 KB | None | 0 0
  1. -- Table saving and reading from files API
  2. -- by PaymentOption
  3. -- for evil of ccnet.
  4.  
  5. -- Takes a table and saves it to a file.
  6. function saveTable(tTable, sFileName)
  7.     if type(tTable) == "table" then
  8.         if not fs.isDir(sFileName) then
  9.             local fileHandle = fs.open(sFileName, "w")
  10.  
  11.             for nIndex, sValue in pairs(tTable) do
  12.                 if type(sValue) ~= "table" then
  13.                     fileHandle.writeLine(sValue)
  14.                 else
  15.                     fileHandle.close()
  16.                     error("Cannont write subtables.")
  17.                 end
  18.             end
  19.  
  20.             fileHandle.close()
  21.         else
  22.             error("Cannon save " .. tTable .. " as a directory.")
  23.         end
  24.     else
  25.         error("Cannont save " .. tTable .. " because it is not a table.")
  26.     end
  27. end
  28.  
  29. -- Takes a file path and attempts to read the contents into a table.
  30. function readTable(sFileName)
  31.     if not fs.isDir(sFileName) and fs.exists(sFileName) then
  32.         local tTable = {}
  33.  
  34.         local nFileLength_Lines = 0
  35.         local fileHandle = io.open(sFileName, "r")
  36.  
  37.         for sLine in fileHandle:lines() do
  38.             nFileLength_Lines = nFileLength_Lines + 1
  39.         end
  40.         fileHandle:close()
  41.  
  42.         fileHandle = fs.open(sFileName, "r")
  43.         local sValueRead = ""
  44.         for nLine=1, nFileLength_Lines do
  45.             sValueRead = fileHandle.readLine()
  46.             if tonumber(sValueRead) then
  47.                 table.insert(tTable, tonumber(sValueRead))
  48.             else
  49.                 table.insert(tTable, sValueRead)
  50.             end
  51.         end
  52.         fileHandle.close()
  53.  
  54.         return tTable
  55.     else
  56.         error("Cannot read a dreictory or a non-existant file.")
  57.     end
  58. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement