A utility script for handling settings files, using ConfigFiles as an intermediary.
Includes documentation comments and (some) error checking.
Copy
class_name SaveLoader
static func save_to_file(
path:String,
source:Object,
template:Dictionary = source.get("defaults")
) -> Error:
var output = ConfigFile.new()
var verify = _verify(template)
if verify != OK: return verify
for section in template.keys():
for value in template[section].keys():
output.set_value(section,value,source.get(value))
return output.save(path)
static func save_to_new_config(
source:Object,
template:Dictionary = source.get("defaults")
)->ConfigFile:
var output = ConfigFile.new()
var verify = _verify(template)
if verify != OK: return null
for section in template.keys():
for value in template[section].keys():
output.set_value(section,value,source.get(value))
return output
static func save_to_config(
source:Object,destination:ConfigFile,
template:Dictionary = source.get("defaults")
)->Error:
var verify = _verify(template)
if verify != OK: return verify
for section in template.keys():
for value in template[section].keys():
destination.set_value(section,value,source.get(value))
return OK
static func load_from_config(
config:ConfigFile,destination:Object,
template:Dictionary[String,Dictionary] = destination.get("defaults")
)->Error:
var verify = _verify(template)
if verify != OK: return verify
for section in template.keys():
for key in template[section].keys():
destination.set(key,config.get_value(section,key,template[section][key]))
return OK
static func load_from_file(
path:String,destination:Object,
template:Dictionary[String,Dictionary] = destination.get("defaults")
)->Error:
var input = ConfigFile.new()
var file_load = input.load(path)
if file_load != OK: return file_load
return load_from_config(input,destination,template)
static func load_defaults(
destination:Object,
template:Dictionary[String,Dictionary] = destination.get("defaults")
)->Error:
var verify = _verify(template)
if verify != OK: return verify
for section in template.keys():
for key in template[section].keys():
destination.set(key,template[section][key])
return OK
static func _verify(template) -> Error:
if template == null:
push_error("Template is missing.")
return ERR_DOES_NOT_EXIST
if template is not Dictionary:
push_error("Template is not a Dictionary.")
return ERR_INVALID_PARAMETER
if template.is_typed() and template is not Dictionary[String,Dictionary]:
push_error("Template has the wrong types, should be Dictionary[String,Dictionary].")
return ERR_INVALID_DATA
for section in template.keys():
if section is not String:
push_error("Template has one or more non-String section keys.")
return ERR_INVALID_DATA
if template[section] is not Dictionary:
push_error("Template has one or more non-Dictionary sections.")
return ERR_INVALID_DATA
for key in template[section].keys():
if key is not String:
push_error("Template has one or more sections containing non-String keys.")
return ERR_INVALID_DATA
return OK