Skip to content

Instantly share code, notes, and snippets.

@amekusa
Last active October 1, 2025 16:35
Show Gist options
  • Select an option

  • Save amekusa/92935d8e554fce397d10292fe3fe87f7 to your computer and use it in GitHub Desktop.

Select an option

Save amekusa/92935d8e554fce397d10292fe3fe87f7 to your computer and use it in GitHub Desktop.
Convert JS value into Lua representation
/**
* Convert JS value into Lua representation
* @author github.com/amekusa
*/
function parse(data, depth = 0) {
switch (typeof data) {
case 'object':
if (!data) return 'nil';
depth++;
let indent = ' '.repeat(depth);
let r = '{\n';
if (Array.isArray(data)) {
for (let i = 0; i < data.length; i++) {
r += `${indent}${parse(data[i], depth)},\n`;
}
} else {
let keys = Object.keys(data);
for (let i = 0; i < keys.length; i++) {
let k = keys[i];
r += `${indent}${k} = ${parse(data[k], depth)},\n`;
}
}
return r + indent.substring(0, 2 * (depth - 1)) + '}';
case 'string':
return `'${data}'`;
case 'boolean':
return data ? 'true' : 'false';
default:
return `${data}`;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment