How to make a function in Haxe that reads content from text file and does something with each line?

How can I make a function in Haxe that reads a line from a text file, prints it/saves it to a variable, and then goes to the next line?

My objective is to make the dialogues on a text file, having the code read a line, and if the first word (a keyword like 'Dialogue01') is found, it reads all the text after such keyword on the same line and it checks the next line for another keyword or a different command to notify the game to advance or show the next dialogue.

• I think you need to break your problem down into smaller parts. Start with learning how to read text files and how to use conditionals. When you're stuck on a problem it's best to break it down into its base components and see if you can figure out how to do the little things. Then you just have to figure out how to combine them. – MichaelHouse Dec 22 '14 at 1:44

First parse the text to a list with something like this

private function parseText(text:String):Array<String>
{
var dialog:Array<String>=new Array();
var lines:Array = text.split("\n");// split in all lines
var line:String;
while (lines.length>0)
{
line= lines.shift().replace("\r", "");// remove more hidden info...
if (line.length != 0)
{
//you can create a switch if you are not just adding dialogues
// just add if(line.indexOf("Dialogue")!=-1)
dialog.push(line);
}
}
}


After that it's easier to work with each line. If you want to use codes for example Dialogue01 is better to add another char like : or _ at the end of the word to identify key words. Use the split(":") function to separate the parts. That way you can separate a line with your char. In the right side you get your line and on the left side you get your keyword "Dialogue" and the rest can be parsed as a number. That way you dont have to worry to write Dialogue01: or Dialogue1: or Dialogue1234:

• This is great! But I still have a problem, I don't know how to parse a file into a string with haxe. I'm stuck in that part. – Javier Bullrich Dec 22 '14 at 3:44
• If you want to load the file in run-time, use haxe.Http or flash.net.URLLoader. Embedding the file at compile-time is simpler: use -resource. – Andy Li Dec 22 '14 at 4:46

You can try my open source TextParser class in HaXe: http://bruce-lab.blogspot.com/2014/11/textparser-simple-class-for-parsing.html (tutorial)

The class is very simple, functions ReadInteger() and ReadString() can be used to get string or integer from a text file. Function GotoNextLine() can move the position of the file pointer to the next line. The class has been use in my JiuGongGe UI for reading layout from a text file.

If you have any problem with the class, let me know.

• Also, the class works on every target that HaXe supports. – user1100006 Dec 22 '14 at 3:40
• Thanks, but I ended up using the other method. – Javier Bullrich Dec 22 '14 at 4:11