Advertisement
ReDestroyDeR

config_api.lua

Oct 15th, 2021 (edited)
420
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.13 KB | None | 0 0
  1. local json = require ("json")
  2.  
  3. CURRENT_PATH = shell.dir()
  4. Config = {}
  5.  
  6. function Config:new(name)
  7.     local private = {}
  8.         private.name = name
  9.  
  10.     local public = {}
  11.         public.properties = {}
  12.         function public:size()
  13.             local count = 0
  14.             for _, _ in pairs(public.properties) do
  15.                 count = count + 1
  16.             end
  17.             return count
  18.         end
  19.  
  20.         function public:fetchFromFile()
  21.             local file = io.open(CURRENT_PATH .. "/" .. private.name .. ".json", "r")
  22.             if file == nil then
  23.                 return
  24.             end
  25.  
  26.             io.input(file)
  27.             local json_data_string = io.read("a");
  28.  
  29.             if (#json_data_string == 0) then
  30.                 io.close(file)
  31.                 return
  32.             end
  33.  
  34.             public.properties = json.decode(json_data_string)
  35.             io.close(file)
  36.         end
  37.  
  38.         function public:updateFile()
  39.             local file = io.open(CURRENT_PATH .. "/" .. private.name .. ".json", "w")
  40.             if file == nil then
  41.                 return
  42.             end
  43.  
  44.             io.output(file)
  45.             local json_data = json.encode(public.properties)
  46.             io.write(json_data)
  47.             io.flush()
  48.             io.close(file)
  49.         end
  50.  
  51.  
  52.     public:fetchFromFile()
  53.     setmetatable(public, self)
  54.     self.__index = self; return public
  55. end
  56.  
  57. return {
  58.     Config = Config
  59. }
  60.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement