Advertisement
Lyqyd

Configuration API

Jan 17th, 2015
5,380
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. --[[
  2. The MIT License (MIT)
  3.  
  4. Copyright (c) 2014 Lyqyd
  5.  
  6. Permission is hereby granted, free of charge, to any person obtaining a copy
  7. of this software and associated documentation files (the "Software"), to deal
  8. in the Software without restriction, including without limitation the rights
  9. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. copies of the Software, and to permit persons to whom the Software is
  11. furnished to do so, subject to the following conditions:
  12.  
  13. The above copyright notice and this permission notice shall be included in
  14. all copies or substantial portions of the Software.
  15.  
  16. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. THE SOFTWARE.
  23. --]]
  24.  
  25. function load(path, _env)
  26.     --load a configuration file, given a fully-resolved path and an optional environment.
  27.     if not fs.exists(path) or fs.isDir(path) then return nil, "not a file" end
  28.     local env
  29.     if not _env then
  30.         --if we were not provided an environment, create one.
  31.         env = setmetatable({}, {__index = _G})
  32.     else
  33.         env = _env
  34.     end
  35.     local fn, err = loadfile(path)
  36.     if fn then
  37.         setfenv(fn, env)
  38.         local success, err = pcall(fn)
  39.         if success then
  40.             --strip the metatable from the environment before returning it.
  41.             return setmetatable(env, {})
  42.         else
  43.             return nil, err
  44.         end
  45.     else
  46.         return nil, err
  47.     end
  48. end
  49.  
  50. function save(path, config)
  51.     if not config or type(config) ~= "table" then return nil, "Not a configuration" end
  52.     local handle = io.open(path, "w")
  53.     if handle then
  54.         for k, v in pairs(config) do
  55.             local success, str = pcall(textutils.serialize, v)
  56.             if success then
  57.                 handle:write(k.." = "..str.."\n\n")
  58.             end
  59.         end
  60.         handle:close()
  61.     else
  62.         return nil, "Could not write configuration."
  63.     end
  64. end
Advertisement
RAW Paste Data Copied
Advertisement