+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?

in Engine by (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.

by (262 points)
selected by

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.
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.