Godot Engine key-value based database

2018 04 22 No Comments

Hello
Here are you simple database for Godot Engine. I got inspired from this answer at godotengine qa.

func SetValue(key, value):
	var data = {key: value}
	var file = File.new()
	if file.open("user://shared_pref.sav", File.WRITE) != 0:
	    print("Error opening file")
	    return
	
	# Save the dictionary as JSON (or whatever you want, JSON is convenient here because it's built-in)
	file.store_line(to_json(data))
	file.close()


func GetValue(key):
	var file = File.new()
	if not file.file_exists("user://shared_pref.sav"):
	    print("No file saved!")
	    return
	
	# Open existing file
	if file.open("user://shared_pref.sav", File.READ) != 0:
	    print("Error opening file")
	    return
	
	# Get the data
	var data = {}
	data = parse_json(file.get_line())
	if data.has(key):
		return data[key]
	else:
		print(key, " [key] not assigned in saved_data")
		return 0

Save above file named Database.gd … To use it import like this:

onready var Database = preload("res://Database.gd").new()

Here you are ready to save values to database:

Database.SetValue("SomeValue", "test")
var foo = Database.GetValue("SomeValue")
print(foo)

Enjoy..