'When writing to a file in godot the value on saves once

I am trying to store the number of coins the player has collected in a file so that items can be purchased from a shop.

I have the below code which successfully writes a value to a file.

func save_coins(coins):
    var coins_str = str(coins)
    var file = File.new() # creates file
    file.open(save_path, File.WRITE) # opens file with ability to write
    file.store_var(coins_str) # stores coins 
    file.close()

Yet for this to successfully work, I had to convert the integer value of the coin variable to a string, as otherwise the value would not write to the file (for some reason it only works for me when the data type of the variable is a string), i.e. when the line file.store_var() is run the integer value of the coin variable is passed, however, this results in no data value in the file - any ideas why?

The save_coins function is called from another function that is connected to a signal - the signal is emitted when the player reaches the end of the level.

When the code is initially run, 8 is found in the file - as there were 8 coins collected, however, after this no other value is added into the file.

Is this because it is overwriting the data - if so how would I avoid this. And most desirably, if you did have any idea on how I could get the integer value being stored instead of the string, could this be written onto a new line of the file?

Thanks Alot.



Solution 1:[1]

Storing an int with store_var should work. Are you sure what you were trying to store was an int? Also, by the way, store_var does not result in an human readable format.


Sadly Godot does not have an append mode. There was an issue, but it fell through amidst the change to the proposal system.

You can workaround it like this:

var file = File.new() # creates file
if file.file_exists(save_path):
    file.open(save_path, File.READ_WRITE)
    file.seek_end()
else:
    file.open(save_path, File.WRITE_READ)

# …
file.close()

This workaround is not great, since this is how you get a time-of-check to time-of-use bug.

I don't think you really want to append the number of coins. It makes sense to overwrite it. Furthermore, if you are going to store multiple things on the same file, don't have a function to save each thing (each one opening and closing the file), instead have a representation of everything you want to store in the file, and have a function that saves that (opening and closing the file only once).


As per alternatives, you can use str2var and var2str, which you can combine with store_pascal_string and get_pascal_string like this:

# save
file.store_pascal_string(var2str(variable))

# load
var variable = str2var(file.get_pascal_string())

These should be human readable, by the way.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Theraot