python中的lua解析器
luaparser的Python项目详细描述
py lua解析器
用python编写的lua解析器和ast构建器。
它既是一个开发库,也是一个命令行工具。
安装:
该软件包可以通过pip安装:
$ python3.6 -m pip install luaparser
它将安装shell命令'luaparser'。
选项
以下是命令行标志:
用法:luaparser[选项]文件名
CLI Options: --version Show program's version number and exit -h, --help Show this help message and exit -s, --source Source passed in a string -x, --xml Set output format to xml -o, --output Write output to file
快速启动
处理AST树
最小示例:
fromluaparserimportastsrc=""" local function sayHello() print('hello world !') end sayHello() """tree=ast.parse(src)print(ast.toPrettyStr(tree))
将显示:
Chunk: {} 1 key body: {} 1 key Block: {} 1 key body: [] 2 items 0: {} 1 key LocalFunction: {} 3 keys name: {} 1 key Name: {} 1 key id: "sayHello" args: [] 0 item body: [] 1 item 0: {} 1 key Call: {} 2 keys func: {} 1 key Name: {} 1 key id: "print" args: [] 1 item 0: {} 1 key String: {} 1 key s: "hello world !" 1: {} 1 key Call: {} 2 keys func: {} 1 key Name: {} 1 key id: "sayHello" args: [] 0 item
您可以使用ast.walk(tree):
fromluaparserimportastfromluaparserimportastnodestree=ast.parse("local foo = 'bar'")fornodeinast.walk(tree):ifisinstance(node,astnodes.Name):process(node)
或者,您可以使用节点访问者:
fromluaparserimportastfromluaparserimportastnodessrc="local a = 42"classNumberVisitor(ast.ASTVisitor):defvisit_Number(self,node):print('Number value = '+str(node.n))tree=ast.parse(src)NumberVisitor().visit(tree)
命令行
给定:
localfunctionlog(msg)print(msg)endlog("hello world !")
$ luaparser source.lua
将输出:
{"Chunk":{"body":{"Block":{"body":[{"LocalFunction":{"name":{"Name":{"id":"log"}},"args":[{"Name":{"id":"msg"}}],"body":{"Block":{"body":[{"Call":{"func":{"Name":{"id":"print"}},"args":[{"Name":{"id":"msg"}}]}}]}}}},{"Call":{"func":{"Name":{"id":"log"}},"args":[{"String":{"s":"hello world !"}}]}}]}}}}