From 0ab35178ab6991378b281c6dadf9cd12e6f452d0 Mon Sep 17 00:00:00 2001 From: aixianling Date: Thu, 2 Jan 2025 17:48:16 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=B7=BB=E5=8A=A0=20JSON=20=E8=BD=AC?= =?UTF-8?q?=20Lua=20=E9=85=8D=E7=BD=AE=E6=96=87=E4=BB=B6=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 json2lua.js 脚本,用于将 JSON 文件转换为 Lua 配置文件 - 更新 .gitignore 文件,忽略 luaConfigs 目录中的 StdItems.config 文件 --- .gitignore | 1 + json2lua.js | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+) create mode 100644 json2lua.js diff --git a/.gitignore b/.gitignore index a081583..e08c6c1 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,4 @@ package-lock.json config.xml /dist.zip dist/ +luaConfigs/StdItems.config diff --git a/json2lua.js b/json2lua.js new file mode 100644 index 0000000..78be4a3 --- /dev/null +++ b/json2lua.js @@ -0,0 +1,51 @@ +const { log } = require('console'); +const fs = require('fs') +const path = require('path'); +const folderPath = "./configs" +function jsonToLua(jsonObj, indent = '', linefeed = '\n') { + let luaStr = ''; + const strKey = key => isNaN(key) ? `${key}` : `[${key}]`; + for (let key in jsonObj) { + let value = jsonObj[key]; + key = strKey(key) + if (typeof value === 'object' && value !== null && !Array.isArray(value)) { + // 对象 + luaStr += `${indent}${key} = {`; + luaStr += jsonToLua(value, indent + ' '); + luaStr += `${indent}},\n`; + } else if (Array.isArray(value)) { + // 数组 + luaStr += `${indent}${key} = {`; + value.forEach(item => { + + if (typeof item === 'string') { + luaStr += `${indent} '${item}',`; + } else { + luaStr += `{${jsonToLua(item, '', '')}},`; + } + }); + luaStr += `${indent}},\n`; + } else { + // 基础类型 + if (typeof value === 'string') { + luaStr += `${indent}${key}="${value}",${linefeed}`; + } else { + luaStr += `${indent}${key} = ${value},${linefeed}`; + } + } + } + return luaStr; +} +const start = () => { + const files = fs.readdirSync(folderPath); + + // 过滤出所有的 JSON 文件 + const jsonFiles = files.filter(file => path.extname(file) === '.json').filter(file => ["StdItems"].map(e => `${e}.json`).includes(file)); + jsonFiles.forEach(file => { + const json = JSON.parse(fs.readFileSync(path.join(folderPath, file), 'utf8')) + const filename = path.basename(file, path.extname(file)); + const luaConfig = `${filename}={\n${jsonToLua(json)}\n}` + fs.writeFileSync(`./luaConfigs/${filename}.config`, luaConfig); + }); +} +start() \ No newline at end of file