You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python提取Lua文件中的所有函数调用及对应参数

实现方案

首先不推荐用正则实现该需求,正则无法处理Lua代码中字符串含括号、参数换行、嵌套调用等复杂边界场景,识别准确率极低,建议直接通过AST解析实现。

第一步:安装依赖

Python生态有成熟的Lua语法解析库luaparser,直接用pip安装即可:

pip install luaparser

第二步:编写解析代码

通过luaparser将Lua代码解析为抽象语法树(AST),遍历AST筛选函数调用节点,提取对应函数名和参数即可:

from luaparser import ast
from collections import defaultdict

def extract_lua_function_calls(lua_content: str) -> dict:
    call_result = defaultdict(list)
    # 解析Lua代码生成AST
    ast_tree = ast.parse(lua_content)
    # 遍历所有AST节点
    for node in ast.walk(ast_tree):
        # 筛选函数调用类型的节点
        if isinstance(node, ast.Call):
            func_node = node.func
            # 只处理直接调用的全局函数,如需处理方法调用可扩展此处逻辑
            if isinstance(func_node, ast.Name):
                func_name = func_node.id
                param_list = []
                for arg in node.args:
                    # 提取字符串字面量参数,可根据需求扩展数字、变量名等其他类型的处理逻辑
                    if isinstance(arg, ast.String):
                        param_list.append(arg.s)
                    elif isinstance(arg, ast.Number):
                        param_list.append(arg.n)
                call_result[func_name] = param_list
    return dict(call_result)

# 测试示例
if __name__ == "__main__":
    test_lua_code = """
function displayText (text)
    print(text)
end

sendGreetings = function(sender, reciever) 
    print("Hi " ..reciever.. " greetings from " ..sender.. "!")
end

displayText("Hello, World!")

sendGreetings("Roger", "Michael")
"""
    print(extract_lua_function_calls(test_lua_code))
    # 输出:{'displayText': ['Hello, World!'], 'sendGreetings': ['Roger', 'Michael']}

注意事项

  • 上述示例默认只提取字面量类型的参数,如果需要保留变量名、表达式等参数形式,可自行扩展参数处理分支的逻辑。
  • 如需解析本地Lua文件,只需读取文件内容传入extract_lua_function_calls函数即可。
  • 该库支持Lua 5.1/5.2/5.3的语法规范,覆盖绝大多数常用场景。

内容的提问来源于stack exchange,提问作者Roger A. Cooper

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 22:27:04