如何在Java类中获取Lua函数的参数名?

有没有办法获取.lua文件中定义的所有函数参数的名称和数量?

比如我的test1.lua是这样的

function MyAdd( num1, num2, num3)
    local x = 0
    if(num1 <= num2) then
        x = num1 + num2 + num3
    else
        x = (num1 - num2) + num3
    end
    return x
end

我正在试图通过传递参数值来执行此函数

如果这个Lua函数是由其他用户编写并保存在一个文件夹中的,Java应用程序在不知道其中包含什么函数的情况下加载该Lua文件。我如何在Java中获取该函数的名称(' MyAdd '),该函数的输入参数数量以及这些输入参数的名称(num1,num2和num3)

如果我知道函数的名称和输入参数的数量和顺序,我可以像下面这样调用函数.

public static void main(String[] args) {

    int a1 = 5;
    int a2 = 10;
    int a3 = 15;

    Globals globals = JsePlatform.standardGlobals();
    globals.get("dofile").call(LuaValue.valueOf("./luascripts/test1.lua"));

        LuaValue MyAdd = globals.get("MyAdd");

        Varargs results = MyAdd.invoke(LuaValue.varargsOf(new LuaValue
             [] {LuaValue.valueOf(a3), LuaValue.valueOf(a1), LuaValue.valueOf
                 (a2)}));
        System.out.println(results);
}

我希望我对自己要实现的内容表达得清晰明了。谢谢任何帮助。

点赞
用户4402089
用户4402089

我认为没有直接的方法可以完成,所以这是我采取的方法。

仅适用于问题中提到的特定情况。

  1. 将.lua文件的内容读入字符串
  2. 检查字符串是否包含字符串“function”
  3. 找到函数名称的索引
  4. 找到‘(’和‘)’的索引
  5. 从步骤4的索引中获取参数作为子字符串。
  6. 在出现‘,’时拆分子字符串并保存到字符串数组中。
    String FnctionName = null;
    String[] par_array = null;
    try {
        String contents = new String(Files.readAllBytes(Paths.get("./luascripts/test1.lua")));
        if ( contents.contains("function") ) {
            int space = contents.indexOf(" ");
            int left_br = contents.indexOf("(");
            int right_br = contents.indexOf(")");
            FnctionName = contents.substring(space + 1, left_br);
            String params = contents.substring(left_br + 1, right_br);

            par_array = params.replaceAll("\\s+", "").split(",");

            System.out.println(FnctionName);
            for ( String s : par_array ) {
                System.out.println(s);
            }
       }
    } catch ( IOException e ) {
        e.printStackTrace();
    }
2016-10-07 12:30:52