how save arrays or dictionaries

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By lalel345

This code does not work for me to save an array, what am I doing wrong?

func _ready():
	load_score()

func _physics_process(delta):

	if Input.is_action_just_pressed("ui_accept"):
		print(array[0])
		print(array[1])
		array[0] += 1
		array[1] += 1
		save_score()

func save_score():
	var file = File.new()
	file.open(score_file, File.WRITE)
	file.store_var(array[0])
	file.close()

func load_score():
	var file = File.new()
	file.open(score_file, File.READ)
	array = file.get_as_text()
	file.close()





	
   
:bust_in_silhouette: Reply From: jgodfrey

Here’s some basic persistence code that can save and load a dictionary (as JSON)…

onready var persistFile = "user://savedata.txt"
onready var saveHandle = File.new()
var saveDict

func _ready():
	saveDict = {
		SCORE: 0,
		COIN_COUNT: 0,
		SOUNDFX_ISMUTED: false,
		MUSIC_ISMUTED: false
	}

func saveUserData():
	saveHandle.open(persistFile, File.WRITE)
	saveHandle.store_line(to_json(saveDict))
	saveHandle.close()

func loadUserData():
	# If we don't yet have a save file to load, create a default one...
	if !saveHandle.file_exists(persistFile):
		saveUserData()

	saveHandle.open(persistFile, File.READ)
	saveDict = parse_json(saveHandle.get_line())
	saveHandle.close()
:bust_in_silhouette: Reply From: MiltonVines

Let’s look at a small example:

In [819]: N
Out[819]: 
array([[  0.,   1.,   2.,   3.],
       [  4.,   5.,   6.,   7.],
       [  8.,   9.,  10.,  11.]])

In [820]: data={'N':N}

In [821]: np.save('temp.npy',data)

In [822]: data2=np.load('temp.npy')

In [823]: data2
Out[823]: 
array({'N': array([[  0.,   1.,   2.,   3.],
       [  4.,   5.,   6.,   7.],
       [  8.,   9.,  10.,  11.]])}, dtype=object)

np.save is designed to save numpy arrays. data is a dictionary. So it wrapped it in a object array, and used pickle to save that object. Your data2 probably has the same character.

You get at the array with:

In [826]: data2[()]['N']
Out[826]: 
array([[  0.,   1.,   2.,   3.],
       [  4.,   5.,   6.,   7.],
       [  8.,   9.,  10.,  11.]])