我想使用 python 搜索 Lua 檔案中的所有函式呼叫。例如,我有這個 Lua 代碼:
function displayText (text)
print(text)
end
sendGreetings = function(sender, reciever)
print("Hi " ..reciever.. " greetings from " ..sender.. "!")
end
displayText("Hello, World!")
sendGreetings("Roger", "Michael")
我希望我的 python 代碼在該代碼中搜索函式呼叫并回傳一個包含函式名稱和引數的字典,所以輸出應該是這樣的:
# {function_name: [param1, param2]}
{"displayText": ["Hello, World!"], "sendGreetings": ["Roger", "Michael"]}
我試圖通過使用正則運算式來實作它,但我遇到了各種各樣的問題,而且結果不準確。另外,我不相信有適用于 Python 的 Lua 決議器。
uj5u.com熱心網友回復:
您可以使用luaparser( pip install luaparser) 和遞回來遍歷ast:
import luaparser
from luaparser import ast
class FunCalls:
def __init__(self):
self.f_defs, self.f_calls = [], []
def lua_eval(self, tree):
#attempts to produce a value for a function parameter. If value is a string or an integer, returns the corresponding Python object. If not, returns a string with the lua code
if isinstance(tree, (luaparser.astnodes.Number, luaparser.astnodes.String)):
return tree.n if hasattr(tree, 'n') else tree.s
return ast.to_lua_source(tree)
def walk(self, tree):
to_walk = None
if isinstance(tree, luaparser.astnodes.Function):
self.f_defs.append((tree.name.id, [i.id for i in tree.args]))
to_walk = tree.body
elif isinstance(tree, luaparser.astnodes.Call):
self.f_calls.append((tree.func.id, [self.lua_eval(i) for i in tree.args]))
elif isinstance(tree, luaparser.astnodes.Assign):
if isinstance(tree.values[0], luaparser.astnodes.AnonymousFunction):
self.f_defs.append((tree.targets[0].id, [i.id for i in tree.values[0].args]))
if to_walk is not None:
for i in ([to_walk] if not isinstance(to_walk, list) else to_walk):
self.walk(i)
else:
for a, b in getattr(tree, '__dict__', {}).items():
if isinstance(b, list) or 'luaparser.astnodes' in str(b):
for i in ([b] if not isinstance(b, list) else b):
self.walk(i)
把它們放在一起:
s = """
function displayText (text)
print(text)
end
sendGreetings = function(sender, reciever)
print("Hi " ..reciever.. " greetings from " ..sender.. "!")
end
displayText("Hello, World!")
sendGreetings("Roger", "Michael")
"""
tree = ast.parse(s)
f = FunCalls()
f.walk(tree)
print(dict(f.f_defs)) #the function definitions with signatures
calls = {a:b for a, b in f.f_calls if any(j == a for j, _ in f.f_defs)}
print(calls)
輸出:
{'displayText': ['text'], 'sendGreetings': ['sender', 'reciever']}
{'displayText': ['Hello, World!'], 'sendGreetings': ['Roger', 'Michael']}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/314397.html
