akadoc/Assets/src/TwoDA.cs

89 lines
2.1 KiB
C#
Raw Normal View History

2014-11-08 21:24:42 +00:00
using UnityEngine;
using System.Collections.Generic;
using System.Text.RegularExpressions;
2014-11-08 21:24:42 +00:00
public class TwoDA : UnityEngine.Object {
2014-11-08 21:24:42 +00:00
public TwoDA(string filepath) {
2014-11-08 21:24:42 +00:00
// Read the file and display it line by line.
System.IO.StreamReader file = new System.IO.StreamReader(filepath);
2014-11-08 21:24:42 +00:00
string line = file.ReadLine();
m_header = line.Split((string[])null, System.StringSplitOptions.RemoveEmptyEntries);
2014-11-08 21:24:42 +00:00
int nCols = m_header.Length;
m_data = new List<string[]>();
2014-11-08 21:24:42 +00:00
int nFileLine = 1;
while((line = file.ReadLine()) != null)
{
if(line[0] != '#'){//Ignore commented lines
MatchCollection matches = m_rgxField.Matches(line);
if(matches.Count == nCols){
int nLine = int.Parse(matches[0].Value);
string[] buff = new string[nCols-1];
2014-11-08 21:24:42 +00:00
for(int i=0 ; i<nCols-1 ; i++){
if(matches[i+1].Groups[1].Success)//Match one word
buff[i] = matches[i+1].Groups[1].Value;
else if(matches[i+1].Groups[2].Success)//Match multi word
buff[i] = matches[i+1].Groups[2].Value;
2014-11-08 21:24:42 +00:00
}
m_data.Add(buff);
2014-11-08 21:24:42 +00:00
}
else
Debug.LogWarning(filepath+": line "+nFileLine.ToString()+" ignored. Found "+matches.Count.ToString()+" columns instead of "+nCols.ToString());
2014-11-08 21:24:42 +00:00
}
2014-11-08 21:24:42 +00:00
nFileLine++;
}
2014-11-08 21:24:42 +00:00
file.Close();
}
2014-11-08 23:40:35 +00:00
public string GetValue(int nRow, string sColumn){
2014-11-08 23:40:35 +00:00
int nCol = FindHeaderCol(sColumn);
if(nCol>=0){
return m_data[nRow][nCol];
2014-11-08 23:40:35 +00:00
}
else{
throw new UnityException("Column '"+sColumn+"' not found in 2DA");
}
2014-11-08 23:40:35 +00:00
}
2014-11-08 21:24:42 +00:00
public override string ToString(){
string sMsg = "";
foreach(string s in m_header){
sMsg += s+"\t";
}
sMsg += "\n";
for(int line=0 ; line<m_data.Count ; line++){
2014-11-08 21:24:42 +00:00
sMsg += line.ToString() + "\t";
for(int col=0 ; col<m_data[line].Length ; col++){
sMsg += m_data[line][col]+"\t";
2014-11-08 21:24:42 +00:00
}
sMsg += "\n";
}
return sMsg;
}
2014-11-08 23:40:35 +00:00
private int FindHeaderCol(string sColName){
for(int i=0 ; i<m_header.Length ; i++){
if(m_header[i] == sColName)
return i-1;
}
return -1;
}
private static Regex m_rgxField = new Regex("(?:\\b([^\\s]+?)\\b|\"([^\"]+?)\")");
2014-11-08 21:24:42 +00:00
private string[] m_header;
private List<string[]> m_data;
}