Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- Configuration API version 2.0
- --[[
- loads a file into a variable
- usage: cfg.load( string file, bool ext )
- * "file" determines the file to load
- * "ext" if true excludes adding ".cfg" to the end of the filename
- returns the file, or "false" and the failure reason ("invalid" or "missing") if it fails
- ]]
- function load( file, ext )
- if not file then
- error( 'Missing expected args' )
- return
- end
- local ext = ext and '' or '.cfg'
- local filename = file .. ext
- if not fs.exists( filename ) then
- return false, 'missing'
- end
- local file = fs.open( filename, 'r' )
- local config = textutils.unserialize( file.readAll() )
- file.close()
- if not config then
- return false, 'invalid'
- end
- return config
- end
- --[[
- loads a file from a variable
- usage: cfg.save( string file, table config, bool ext )
- * "file" determines the file to save
- * "config" is the table to save into the file
- * "ext" if true excludes adding ".cfg" to the end of the filename
- returns true if suceeds
- ]]
- function save( file, config, ext )
- if not file or not config then
- error( 'Missing expected args' )
- return
- end
- local ext = ext and '' or '.cfg'
- local file = fs.open( file .. ext, 'w' )
- file.write( textutils.serialize( config ) )
- file.close()
- return true
- end
- --[[
- write a value to a config file as a key
- usage: cfg.save( string file, any line, any key, bool ext )
- * "file" determines the file to save
- * "line" is the variable to add to the file
- * "key" is the key to write it to
- * "ext" if true excludes adding ".cfg" to the end of the filename
- returns true if suceeds, or false if the file is invalid
- ]]
- function saveLine( file, line, key, ext )
- if not file or not line or not key then
- error( 'Missing expected args' )
- return
- end
- local config, cfgError = load( file, ext )
- config = config or {}
- if cfgError == 'invalid' then
- return false
- end
- config[key] = line
- save( file, config, ext )
- return true
- end
Add Comment
Please, Sign In to add comment