0 votes

After saving and loading type changes TYPEINT to TYPEREAL.
Because of this a many of errors, for example match does not work correctly.

I write an example code below:

var array = ["items", 0]

func test():

    print("TYPE BEFORE: ", typeof(array[1]))
    _save()
    _load()
    print("TYPE AFTER: ", typeof(array[1]))

    pass

func _save():

    var data = {
        example = {
            array = array
        }
    }

    var save_file = File.new()
    save_file.open("res://test.json", File.WRITE)
    save_file.store_line(to_json(data))
    save_file.close()

    pass

func _load():

    var save_file = File.new()
    if(not save_file.file_exists("res://test.json")): return
    save_file.open("res://test.json", File.READ)
    var data = {}
    data = parse_json(save_file.get_as_text())
    array = data['example']['array']
    save_file.close()

    pass

How set default array item type? And how to fix it? Thanks!
Something helps int(array[1]), but I would like a more comprehensive solution.

in Engine by (83 points)
edited by

1 Answer

+1 vote

https://github.com/godotengine/godot/issues/9499
It seems that json converts integers to float. You can convert any float in godot to integer with: int (myfloatvar)

by (2,060 points)

I know about that. Are there any other options how to get around this?
for example, to set the type during loading

In general, I solved the problem. I assign types at loading

Once you load the data (after parse_json ()), you can loop through it, and if it finds a value with real type replace the same value with a type int in the already loaded data. I don't know if it is a very elegant solution but it could work. One problem is that if you want to save floats together with int everything will be converted to int. A solution to the latter could be to also save a string explicitly specifying the type along with the data.

func _load():

    var save_file = File.new()
    if(not save_file.file_exists("res://test.json")): return
    save_file.open("res://test.json", File.READ)
    var data = {}
    data = parse_json(save_file.get_as_text())
    array = data['example']['array']
    save_file.close()

    for i in array.size():
        if typeof(array[i]) == TYPE_REAL:
            array[i] = int(array[i])


    pass

ok, I leave an example below, I had prepared it but it was without internet.

I did about the same, thanks anyway)

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.