+1 vote

I'm new to Godot and wish to parse a file by characters. The file can be quite large so I'd prefer not reading the whole thing as a string. So far I have this:

var file = File.new()
file.open(filename, File.READ)
while !file.eof_reached():
    var character = char(file.get_8())
    if !file.eof_reached():
        print(character) # here I would call my parser

Without the if inside the while the last character is always garbage since the EOF is only reached after executing file.get_8(). As far as I know there is no do while loop in GDscript, so is there a better way to achieve this?

asked Dec 30, 2017 in Engine by Wabbitseason (20 points)

1 Answer

+2 votes
Best answer

This is subjective, but I always prefer for loops over while loop. A habit I acquired working in the embedded area.

var file = File.new()
file.open("res://test.txt", File.READ)
for _ in range(file.get_len() - 1):

Sometimes the "for" version does not look that nice and compact, but it always guaranteed to terminate.

answered Jan 1, 2018 by Artium Nihamkin (260 points)
selected Jan 1, 2018 by Wabbitseason

Your suggestion certainly looks more elegant, but _ as variable name isn't accepted, so I had to replace it to something else, like i. Other than this it's working perfectly. Thank you!

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.