Advertisement
Aadvert

lsave 0.51

Feb 10th, 2012
477
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.86 KB | None | 0 0
  1. local lsave = {} -- will carry the public functions; loadfile does not like globals :/
  2. function lsave.load(sFile) -- This function will check that lsave saved the file in the future.
  3.     if not fs.exists(sFile) then return false, "nofile" end -- We can't load a file that doesn't exist.
  4.     local hHandle = io.open(sFile, "r")
  5.     local err, res = pcall(function() return setfenv(loadfile(sFile),getfenv())() end)
  6.     if not err then
  7.         return false, res
  8.     end
  9.     return true, res
  10. end
  11.  
  12. -- Saving helper format strings/functions
  13. lsave.types = {}
  14. lsave.types.boolean = "data[%q] = %s"
  15. lsave.types.string = "data[%q] = %q"
  16. lsave.types.number = "data[%q] = %d"
  17.     -- Saving function
  18. function lsave.save(sFile, data)
  19.     if type(sFile) ~= "string" or type(data) ~= "table" then
  20.         return false, "Invalid arguments"
  21.     end
  22.     local sData = "local data = {} -- This file, generated by lsave 0.5. Edit at your own risk.\n\n"
  23.     for k, v in pairs(data) do
  24.         local sDataType = type(v)
  25.         local saveHelper = lsave.types[sDataType]
  26.         if not saveHelper then
  27.             -- We have problem, let's just print it, and continue without saving it.
  28.             print("Warning: (saveToFile) unknown data type (ignoring), in key: " .. k)
  29.         else
  30.             -- No errors, save it.
  31.             if type(saveHelper) == "string" then
  32.                 sData = sData .. string.format(saveHelper, k, tostring(v)) .. "\n"
  33.             elseif type(saveHelper) == "function" then -- For the future, and custom stuff.
  34.                 sData = sData .. saveHelper(k, v) .. "\n"
  35.             end
  36.         end
  37.     end
  38.     sData = sData .. "\nreturn data" -- We need to return the config in order to retrieve it.
  39.     -- Delete and save.
  40.     local hHandle, err = io.open(sFile, "w")
  41.     if not hHandle then
  42.         return false, err
  43.     end
  44.     hHandle:write(sData)
  45.     hHandle:close()
  46.     return true
  47. end
  48. return lsave -- This, so you can do "lsave = loadfile("lsave")()"
  49. -- Remove the line if you want to just paste it in your program, instead.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement