Tuesday, November 11, 2014

TextParser - A Simple Class for Parsing Text Files

TextParser is a simple utility HaXe class for parsing text files. You can use this class to read String, Int variables from a text file. For example, the JiuGongGe UI uses a text file to configure the UI layout, so it needs to parse the text configuration file to do the set up.

The source code of the class is released with the JiuGongGe UI:
https://flaswf.googlecode.com/svn/trunk/JiuGongGeUI-v0.2/src/TextParser.hx
TextParser is also available in AS3 as a swc:
https://flaswf.googlecode.com/svn/trunk/JiuGongGeUI-v0.2/swc/TextParser.swc
To use the class, add the following line in your main class first:

haxe.initSwc(this);

The following is a simple AS3 example for using the TextParser class to parse a text file line by line and read some strings and integers needed:
var myUILayout:ByteArray = new myUILayoutClass() as ByteArray;
var myTextParser:TextParser = new TextParser(myUILayout.toString());
while (!myTextParser.EndofFile())
{
var Name:String = myTextParser.ReadString();
trace(Name);
if (Name == "#") //comment line
{
    myTextParser.GotoNextLine();
    continue;
}
var CallBackStr:String = myTextParser.ReadString();
trace(CallBackStr);
var IconStr:String = myTextParser.ReadString();
trace(IconStr);
var Color:uint = myTextParser.ReadInteger();
trace(Color);
var Label:String = myTextParser.ReadString();
trace(Label);
var LevelStr:String = myTextParser.ReadString();
trace(LevelStr);
myTextParser.GotoNextLine();
}
Basically, you need to put the parsing process inside a while loop. Where the function EndofFile() is used to check whether it is the end of the text file. The function GotoNextLine() will move the position of the file pointer to the next line. The functions ReadString() and ReadInteger() are used to read string and integer from the text file and update the file pointer's position.

Full source code for the example:
https://flaswf.googlecode.com/svn/trunk/JiuGongGeUI-v0.2/swc/src/Main_TP.as

For a HaXe code example, please check the JiuGongGe UI's source code. 

No comments:

Post a Comment

Sponsors