最近项目在做C#代码转换Lua代码重构,配置表用的Bytes类型文件,所以写了一个Bytes转Lua的转表工具,方便直接读取配置表数据,奈何主程不让用。以下是代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Text;
namespace BytesTableToLuaTable
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("请输入要转Lua的表名:");
string tableName = Console.ReadLine();
string readPath = "F:\\stargate/LsjProduct/Client/EditorData/Package/Table/"+ tableName;//读取文件路径
string writePath = "F:\\stargate/LsjProduct/Client/LuaScript/Config/"+ tableName;//写入文件文件夹
ReadFirstLine(readPath,writePath);
}
public static void ReadFirstLine(string readPath,string writePath) {
StreamReader sr = new StreamReader(readPath + ".bytes", Encoding.Default);
String line;
Dictionary<int,string> statusDict = new Dictionary<int, string>();
int i = 0;
while ((line = sr.ReadLine()) != null)
{
if (i == 0)
{
string firstString1 = line.ToString().Replace(" "," ");
string firstString2 = firstString1.Replace("\n", " ");
string firstString3 = firstString2.Replace("\t", " ");
string[] firstStringArr = firstString3.Split(' ');
string[] strArr = new string[firstStringArr.Length];
for (int j = 0; j < strArr.Length; j++)
{
strArr[j] = firstStringArr[j].Trim();
statusDict[j] = strArr[j];
Console.WriteLine(strArr[j]);
}
}
break;
}
WriteByStreamWriter(readPath, writePath, statusDict);
}
public static void WriteByStreamWriter(string readPath,string writePath,Dictionary<int,string> statusDict) {
foreach (var item in statusDict)
{
Console.Write(item.Key+":"+item.Value+"\n");
}
StreamReader sr = new StreamReader(readPath+".bytes", Encoding.Default);
String line;
FileStream fs = new FileStream(writePath+".lua", FileMode.Create);
StreamWriter sw = new StreamWriter(fs);
string []pathStringArr = readPath.Split('/');
string tableName = pathStringArr[pathStringArr.Length - 1];
sw.Write(tableName+ " = { \n");//写入表名
int i = 0;
while ((line = sr.ReadLine()) != null)
{
if (i == 0) { i = 1;continue; }
string firstString1 = line.ToString().Replace(" ", " ");
string firstString2 = firstString1.Replace("\n", " ");
string firstString3 = firstString2.Replace("\t", " ");
string[] firstStringArr = firstString3.Split(' ');
string[] strArr = new string[firstStringArr.Length];
for (int j = 0; j < strArr.Length; j++)
{
strArr[j] = firstStringArr[j].Trim();
}
string writeStr= "\t[" + i + "] = { ";
for (int k = 0; k< strArr.Length; k++)
{
writeStr += statusDict[k] + " = \"" + strArr[k] + "\" , ";
}
writeStr += "\"},\n";
sw.Write(writeStr);
i++;
}
sw.Write("}");//结束括号
//清空缓冲区
sw.Flush();
//关闭流
sw.Close();
fs.Close();
}
}
}
工具能转换单个配置表文件成Lua文件,当然也有考虑将整个文件夹内文件批量转换,不过暂时用不上,就不写了。