Files
chuanqi-client-config/tools/lua2json.js
2025-01-17 16:47:39 +08:00

107 lines
3.5 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

const { log } = require('console');
const fs = require('fs');
const path = require('path');
const folderPath = "../luaConfigs"
function parseLuaConfig(luaContent) {
const config = {};
const lines = luaContent.split('\n');
let currentPath = config;
lines.forEach(line => {
line = line.trim();
if (line.startsWith('--')) return; // 跳过注释行
// 匹配键值对
const keyMatch = line.match(/^\s*(\w+)\s*=\s*(.+?),?$/);
if (keyMatch) {
const key = keyMatch[1].trim();
const value = keyMatch[2].trim();
// 尝试解析值
let parsedValue;
if (value === 'true' || value === 'false') {
parsedValue = value === 'true';
} else if (!isNaN(parseFloat(value))) {
parsedValue = parseFloat(value);
} else if (value.startsWith('"') && value.endsWith('"')) {
parsedValue = value.slice(1, -1);
} else if (value.startsWith('{') && value.endsWith('}')) {
parsedValue = parseLuaTable(value);
} else {
parsedValue = value;
}
// 处理嵌套对象
const keys = key.split('.');
keys.reduce((acc, k, i) => {
if (i === keys.length - 1) {
acc[k] = parsedValue;
} else {
acc[k] = acc[k] || {};
return acc[k];
}
}, currentPath);
}
// 匹配表(数组或对象)
const tableMatch = line.match(/^\s*(\w+)\s*=\s*{(.+?)},?$/);
if (tableMatch) {
const key = tableMatch[1].trim();
const tableContent = tableMatch[2].trim();
const parsedTable = parseLuaTable(tableContent);
// 处理嵌套对象
const keys = key.split('.');
keys.reduce((acc, k, i) => {
if (i === keys.length - 1) {
acc[k] = parsedTable;
} else {
acc[k] = acc[k] || {};
return acc[k];
}
}, currentPath);
}
});
return config;
}
// 解析Lua表数组或对象
function parseLuaTable(tableContent) {
const table = [];
const lines = tableContent.split(',').map(line => line.trim());
lines.forEach(line => {
if (line.startsWith('{')) {
const nestedTableContent = line.slice(1, -1).trim();
table.push(parseLuaTable(nestedTableContent));
} else if (line.startsWith('"') && line.endsWith('"')) {
table.push(line.slice(1, -1));
} else if (!isNaN(parseFloat(line))) {
table.push(parseFloat(line));
} else if (line === 'true' || line === 'false') {
table.push(line === 'true');
} else {
table.push(line);
}
});
return table;
}
const scope = ["Monster"]
const start = () => {
const files = fs.readdirSync(folderPath);
// 过滤出所有的 JSON 文件
const luaFiles = files.filter(file => path.extname(file) === '.config').filter(file => scope.map(e => `${e}.config`).includes(file));
luaFiles.forEach(file => {
const luaContent = fs.readFileSync(path.join(folderPath, file), 'utf8')
const filename = path.basename(file, path.extname(file));
const luaConfig = parseLuaConfig(luaContent);
log(luaConfig)
fs.writeFileSync(`../configs/${filename}.json`, luaConfig);
});
}
start()