Read and save arrays [SOLVED]

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

Now here comes my 4. saving problem…

As a result of another question:
https://forum.godotengine.org/70584/shortest-posible-example-for-saving-multiple-variables
I got this code for a simple saving system with two variables:

var level = 1
var leben = 1

func _ready():
    load_level()

func load_level():
    var save_file = File.new()
    if not save_file.file_exists("user://savefile.save"):
        return
    save_file.open("user://savefile.save", File.READ)
    level = int(save_file.get_line())
    leben = int(save_file.get_line())
    save_file.close()

func save_level():
    var save_file = File.new()
    save_file.open("user://savefile.save", File.WRITE)
    save_file.store_line(str(level))
    save_file.store_line(str(leben))
    save_file.close()

Now I changes the level variable into an array:

var level = [1,0,0,0,0,0]

What things must be changed, to save and read an array, because now, I think it, would convert the array into one int value and it wouldnt work any more.
Thanks for answers!

EDIT: I solved it by wriding every index of the array in one line of the saving file with a for function.

:bust_in_silhouette: Reply From: blockchan

Did you try using convert method in GDScript?

level = convert(save_file.get_line(), 19)

19 is array in Variant.Type

I changed this line:

save_file.store_line(str(level))

to this line:

level = convert(save_file.get_line(), 19)

as you said, but I got this:

Invalid call. Nonexistent built-in function ‘convert’.

How can I fix that?

Godot_Starter | 2020-05-13 15:36

:bust_in_silhouette: Reply From: RazorSh4rk

What i would do, is use JSON.

var data = {
'level': 1,
'somethingelse': 2
}

func save():
 # open file
 file.store_line(JSON.print(data))

func load():
 # open file
 data = JSON.parse(file.get_line())

This way you don’t have to reimplement everything if you add a new variable.

My question was more, how I can save arrays and not how I can save normal variables better. But thanks for the tip!

Godot_Starter | 2020-05-14 06:11

Oh, yeah, you can add your array as a field in the json, like {'arr': [1, 2, 3]} and it will still get serialized.

RazorSh4rk | 2020-05-14 12:56