Skip to content

Instantly share code, notes, and snippets.

@Olliebrown
Last active March 14, 2021 19:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Olliebrown/8bf80137284c0c3ec72ab525140d21bd to your computer and use it in GitHub Desktop.
Save Olliebrown/8bf80137284c0c3ec72ab525140d21bd to your computer and use it in GitHub Desktop.
Convert some Lua tables to JS objects
/*
* A quick and dirty script to convert SOME lua tables to JSON objects
*
* This is NOT an attempt at a comprehensive Lua table converter. It
* will catch ones that I encountered a lot in my coding of tabletop
* simulator scripts specifically. I used this to scale and adjust
* hard-coded snap points and other data quickly so I wouldn't have to
* do it by hand
*/
const fs = require('fs')
const JSONC = require('comment-json')
// Read lua from file and attempt to convert
const luaStr = fs.readFileSync('./luaData.lua', { encoding: 'utf8'})
try {
// Read in and parse the Lua table
const obj = luaTableToJSObj(luaStr)
// TODO: Modify the data here (however you want)
// Write out the modified data as a Lua table
fs.writeFileSync('./newLuaData.lua', JSObjToLuaTable(obj), { encoding: 'utf8' })
} catch(err) {
console.error('Failed to parse lua table/JSON')
console.error(err)
}
function luaTableToJSObj (luaString) {
// Convert comments and remove newlines
let JSONString = luaString.replace(/--(.*)/g, '//$1');
JSONString = JSONString.replace(/^\s+?[\r\n]/gm, '')
// Replace all '=' with ':'
JSONString = JSONString.replace(/\=/g, ':');
// Surround keys in quotes
JSONString = JSONString.replace(/([\w]*)\s+\:/g, '"$1":');
// Assume consecutive curly braces indicate arrays
JSONString = JSONString.replace(/{{/g, '[{');
JSONString = JSONString.replace(/}}/g, '}]');
// Catch single-line arrays (with no keys)
JSONString = JSONString.replace(/{([-\.\s\d,]+)}/g, '[$1]');
// Try to parse (might throw an error)
const obj = JSONC.parse(JSONString)
return obj
}
function JSObjToLuaTable (JSObj) {
let luaString = JSONC.stringify(JSObj, null, 2)
// Change multi-line arrays to be in-line
luaString = luaString.replace(/:\s*\[.+?\]/gs, (match) => {
const inLined = match.replace(/\r?\n|\r/g, ' ')
return inLined.replace(/\s+/g, ' ')
});
// Remove quotes around keys
luaString = luaString.replace(/\"(\w*)\"\s*:/g, '$1 :')
// Replace colon with equals
luaString = luaString.replace(/:/g, '=')
// Convert array square-braces to curly-braces
luaString = luaString.replace(/\[/g, '{')
luaString = luaString.replace(/\]/g, '}')
// Convert '//' comments to '--' comments
luaString = luaString.replace(/\/\/(.*)/g, '--$1');
// Return the encoded lua
return luaString
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment