forked from christophrus/lua-to-json
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
50 lines (48 loc) · 1.51 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
'use strict'
var assert = require('assert')
var fs = require('fs')
var luaParser = require('luaparse')
module.exports = function (lua) {
return luaEval(luaParser.parse(lua))
}
function luaEval (ast, parentTable) {
if (ast.type === 'Chunk') {
var table = {}
ast.body.forEach(function (chunk) {
luaEval(chunk, table)
})
return table
} else if (ast.type === 'AssignmentStatement') {
assert(parentTable, "Can't have an assignment statement without a place to put it")
for (var ii = 0; ii < ast.variables.length; ++ii) {
var varInfo = ast.variables[ii]
if (varInfo.type !== 'Identifier') {
console.log('Unknown variable type:', varInfo)
}
parentTable[varInfo.name] = luaEval(ast.init[ii])
}
return parentTable
} else if (ast.type === 'TableConstructorExpression') {
var table;
if (ast.fields.length > 0 && ast.fields[0].type === "TableValue") {
table = []
} else {
table = {}
}
ast.fields.forEach(function (chunk) {
luaEval(chunk, table)
})
return table
} else if (ast.type === 'TableKey') {
assert(parentTable, "Can't have a table key without a table to put it in")
parentTable[luaEval(ast.key)] = luaEval(ast.value)
return parentTable
} else if (ast.type === 'TableValue') {
parentTable.push(luaEval(ast.value))
return parentTable
} else if (/Literal$/.test(ast.type)) {
return ast.value
} else {
console.log('Unknown type:', ast)
}
}