|Topic was automatically imported from the old Question2Answer platform.
I’ve followed the tutorial to set up save/load functionality in my game, but I’m finding that when I load the game any variables in the class which were defineda s integers are not loading. The reason seems to be because the data being passed in the load function is a string rather than integer.
To get around this, I can manually check the name of the variable and if I know it’s an integer, then pass it as an integer, however this requires an if statement for every variable which is an integer. For example:
if i == "guests":
Is there a more efficient way to achieve this? How can the load function determine whether or not the saved value should be an integer and then set the variable accordingly?
My proposal is to use JSON to save and load data put in dictionaries.
The docs have an example for this:
Aside from example you can encode and decode a dictionary to JSON to/from any string.
Hi, yes I followed the steps on that page to set up my save/load functions. However, when I retrieve an integer from the save data and load it back into the dictionary (which is expecting an integer) it fails because the loaded data is a string.
I need to enclose the loaded data in int( ) for it to work, however the code doesn’t know which variables were originally integers and which were originally strings.
derekjwhitten | 2019-04-03 08:39
You don’t have to retrieve the integer from the saved data and then put it into a dictionary.
Just save the whole dictionary as a string (use
to_json(mydictionary)) and retrieve it later from the file as a string (use
mydictionary = parse_json(justreadstring)).
@GDScript — Godot Engine (3.1) documentation in English
If a dictionary is encoded in JSON then strings are quoted but numbers are not. So after reading and parsing the data back the types should be ok again.
Or is there any important reason why you can’t save your data as JSON text?
wombatstampede | 2019-04-03 09:24
Ok thanks, I think that makes sense.
Is there a reason why in the ‘saving games’ example they loop through each variable and save it to the loaded object?
# Now we set the remaining variables.
for i in current_line.keys():
if i == "filename" or i == "parent" or i == "pos_x" or i == "pos_y":
derekjwhitten | 2019-04-03 11:18
Honestly, I don’t understand the reason which is told there.
I think it is much easier by just storing one dictionary per file as JSON.
You might also read the whole file in the string when doing it this way.
data = file.get_as_text()
What I also did, was storing a backup of the save game (and falling back to it if loading of the original save game fails) and also renaming the stored file to the final file name only after it was saved without errors. But those are more complicated tasks you might want to try later.
wombatstampede | 2019-04-03 11:57