There are several things wrong with your code, some of them you didn't noticed:
var word_list = [loadWords()]
This is never going to give you an array of words. Instead, it will give you an array with one entry, and this single entry will contain whatever loadWords
returns. Don't use the square brackets.
return file_string
file.close();
You returned before closing the file. return
should be used as the very last instruction, because everything after it will never be executed.
var file_string = file.get_as_text();
This is going to read the whole file as a single string. You could think your print is fine, but that's actually because you are just printing the whole file with the \n
characters, not the words.
So how to get an actual list of words?
Instead of file.get_as_text()
, you can use this function:
static func get_lines(file):
var lines = []
while not file.eof_reached():
lines.append(file.get_line())
return lines
Assuming your file contains one word per line, this will read them one by one to fill an array of words, which is then returned.
Then, picking a random word will be easy at this point:
var word = words[randi() % words.size()]