Godot-docs: error checking file.get_line().empty() ( is always false )

Created on 9 Jul 2020  路  2Comments  路  Source: godotengine/godot-docs

Godot version:
3.2.2

OS/device including version:
Ubuntu Studio 20.04 lts

Issue description:

If the file is empty i get this error:

E 0:00:28.982 call: Error parsing JSON at line 0:
cpp:1268 @ call()
global_chat.gd:570 @ _load_mensajes_privados_user()
session.gd:54 @ _ready()
global_utiles.gd:699 @ _carga_backload_de_escena()
global_utiles.gd:790 @ _on_timer_delta_timeout()

So i write some lines to check if the string is NOT empty : if !file.get_line().empty():

and i always get the same error, so y print the result of file.get_line().empty() and i got FALSE and the error is not there
anymore but if i stop printing the result of file.get_line().empty() i get the error again

Steps to reproduce:

Just create a file and then try to load the empty file, you must check if the line is empty. to avoid error just print file.get_line().empty() before the check if empty.

while not file.eof_reached():

    print(file.get_line().empty())  <- walkarround  --- this way you avoid the error 

       if !file.get_line().empty():

        if parse_json( file.get_line() ) != null:

            var current_line : Dictionary  = parse_json(file.get_line())

            for i in current_line:

                dict_mensajes_privados_user[i] = current_line[i]
bug class reference

Most helpful comment

The current note in the documentation is probably too vague. It should be updated to provide a clear gdscript example to describe how to actually iterate over the file:
https://docs.godotengine.org/en/stable/classes/class_file.html#class-file-method-eof-reached

All 2 comments

This is similar to godotengine/godot#16919 & godotengine/godot#31464, eof_reached() is not reliable for parsing a file.

You can fix it by setting your while loop this way instead:

while file.get_position() < file.get_len():
    var current_line = parse_json(file.get_line())

This tutorial has a full example:
https://docs.godotengine.org/en/latest/tutorials/io/saving_games.html#saving-and-reading-data

The current note in the documentation is probably too vague. It should be updated to provide a clear gdscript example to describe how to actually iterate over the file:
https://docs.godotengine.org/en/stable/classes/class_file.html#class-file-method-eof-reached

Was this page helpful?
0 / 5 - 0 ratings