Advertisement
ndfjay

config api

Jan 9th, 2016
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 2.11 KB | None | 0 0
  1. local function exists(path)
  2.         local file = assert(io.open(path, "r"))
  3.         if file ~= nil then
  4.                 file:close()
  5.                 return true
  6.         end
  7.        
  8.         return false
  9. end
  10.  
  11. local function getTable(path)
  12.         if exists(path) then
  13.                 local file = io.open(path, "r")
  14.                 local lines = {}
  15.                 local i = 1
  16.                 local line = file:read("*l")
  17.                 while line ~= nil do
  18.                         lines[i] = line
  19.                         line = file:read("*l")
  20.                         i = i + 1
  21.                 end
  22.                 file:close()
  23.                 return lines
  24.         end
  25.         return {}
  26. end
  27.  
  28. local function getLine(path, n)
  29.         if exists(path) then
  30.                 local lines = getTable(path)
  31.                 return lines[n]
  32.         end
  33.         return ""
  34. end
  35.  
  36.  
  37. local function fwrite(path, text)
  38.         local file = assert(io.open(path, "w"))
  39.         file:write(text)
  40.         file:close()
  41. end
  42.  
  43.  
  44. local function fwriteFromTable(path, t)
  45.         local text = ""
  46.         for _, line in pairs(t) do
  47.                 text = text..line.."\n"
  48.         end
  49.         fwrite(path, text)
  50. end
  51.  
  52. -- BEGINNING OF CODE
  53.  
  54. function makeConfig( path )
  55.     fwrite(path, "")
  56.     return true
  57. end
  58.  
  59. function loadConfig( path )
  60.     _conf = getTable(path)
  61.     return _conf
  62. end
  63.  
  64. function addConfigLine( path, suffix, value)
  65.     _conf = getTable( path )
  66.     _conf[#_conf+1] = suffix..": "..value
  67.     fwriteFromTable(path, _conf)
  68.     return _conf
  69. end
  70.  
  71. function modifyConfigLine( path, line, suffix, value)
  72.     _conf = getTable( path )
  73.     _conf[line] = suffix..": "..value
  74.     fwriteFromTable(path, _conf)
  75.     return _conf
  76. end
  77.  
  78. function getValue( t, line, isNumber)
  79.     if isNumber then
  80.         _val = tonumber(string.sub(t[line], string.find(t[line], ":")+2))
  81.     else
  82.         _val = string.sub(t[line], string.find(t[line], ":")+2)
  83.     end
  84.     return _val
  85. end
  86.  
  87. function changeValue( path, line, value )
  88.     t = getTable( path )
  89.     _str = string.sub(t[line],1, string.find(t[line], ":"))
  90.     t[line] = _str.." "..value
  91.     fwriteFromTable(path, t)
  92.  
  93.  
  94.     return t
  95. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement