View difference between Paste ID: Sh5CRD02 and Nsz75Dq5
SHOW: | | - or go back to the newest paste.
1
-- Configuration API version 2.0
2
3
--[[
4
loads a file into a variable
5
usage: cfg.load( string file, bool ext )
6
* "file" determines the file to load
7
* "ext" if true excludes adding ".cfg" to the end of the filename
8
returns the file, or "false" and the failure reason ("invalid" or "missing") if it fails
9
]]
10
function load( file, ext )
11
  if not file then
12
    error( 'Missing expected args' )
13
    return
14
  end
15
  local ext = ext and '' or '.cfg'
16
  local filename = file .. ext
17
  if not fs.exists( filename ) then
18
    return false, 'missing'
19
  end
20
  local file = fs.open( filename, 'r' )
21
  local config = textutils.unserialize( file.readAll() )
22
  file.close()
23
  if not config then
24
    return false, 'invalid'
25
  end
26
  return config
27
end
28
29
--[[
30
loads a file from a variable
31
usage: cfg.save( string file, table config, bool ext )
32
* "file" determines the file to save
33
* "config" is the table to save into the file
34
* "ext" if true excludes adding ".cfg" to the end of the filename
35
returns true if suceeds
36
]]
37
function save( file, config, ext )
38
  if not file or not config then
39
    error( 'Missing expected args' )
40
    return
41
  end
42
  local ext = ext and '' or '.cfg'
43
  local file = fs.open( file .. ext, 'w' )
44
  file.write( textutils.serialize( config ) )
45
  file.close()
46
  return true
47
end
48
49
--[[
50
write a value to a config file as a key
51
usage: cfg.save( string file, any line, any key, bool ext )
52
* "file" determines the file to save
53
* "line" is the variable to add to the file
54
* "key" is the key to write it to
55
* "ext" if true excludes adding ".cfg" to the end of the filename
56
returns true if suceeds, or false if the file is invalid
57
]]
58
function saveLine( file, line, key, ext )
59
  if not file or not line or not key then
60
    error( 'Missing expected args' )
61
    return
62
  end
63
  local config, cfgError = load( file, ext )
64
  config = config or {}
65
  if cfgError == 'invalid' then
66
    return false
67
  end
68
  config[key] = line
69
  save( file, config, ext )
70
  return true  
71
end