我试图用pyparsing解析一些LUA函数。它也适用于我需要的几乎所有东西,除了一个最后一个参数只是一个单词的情况。
所以这是我的代码。这是我使用pyparsing的第一个解析器,但我尽力按逻辑结构:
在代码中解释我的评论:
trigger_async(<object>, <name>, <param>)
trigger_async(<parameters>)
<param> = <name> = <type>
def parse_events_from_text(text):
variable = Word(alphanums + "-_.:()")
# Entity on which the event will be triggered
obj = variable.setResultsName("object")
# Name of the event
name = (quotedString + Optional(Suppress("..") + variable)).setResultsName("name")
# Parameter List of the event
paramName = variable.setResultsName("name")
paramType = variable.setResultsName("type")
param = Group(paramName + Suppress("=") + paramType).setResultsName("parameter")
paramList = Group(Optional(Suppress("{") + ZeroOrMore(delimitedList(param)) + Suppress("}"))).setResultsName("parameters")
function_parameter = obj | name | paramList
# Function Start
trigger = "trigger"
async = Optional("_async")
# Function Call
functionOpening = Combine(trigger + async + "(").setResultsName("functionOpening")
functionCall = ZeroOrMore(Group(functionOpening + delimitedList(function_parameter) + Suppress(")")))
resultsList = functionCall.searchString(text)
results = []
for resultsL in resultsList:
if len(resultsL) != 0:
if resultsL not in results:
results.append(resultsL)
return results
所以解析器就是针对那些类型的事件编写的:
trigger(self._entity, 'game:construction:changed', { entity = target })`
trigger_async(entity, 'game:heal:healer_damaged', { healer = entity })`
trigger_async(entity, 'game:heal:healer_damaged', { healer = entity, entity = target, test = party})`
trigger_async(entity, 'game:heal:healer')`
trigger(entity.function(), 'game:heal:healer', {})`
但问题是没有任何花括号:
trigger(entity, 'game:heal:healer', entity.test)
由于我声明的变量
,它不起作用variable = Word(alphanums + "-_.:()")
允许使用大括号,因此解析器与函数结束“缺失”的最后一个混淆。如果我会写
trigger(entity,'game:heal:healer',entity.test))
它会起作用。
我坐下来想重写解析器,但我不知道怎么做?不知怎的,我必须告诉它只有variable
有1个开括号和1个右括号才有效:
trigger(entity,'game:heal:healer',entity.test(input))
否则不要吃那个闭合支撑。
trigger(entity,'game:heal:healer',entity.test) <-- Variable, don't eat it!