LuaJ无法正确提供命令行参数。

我尝试了由luaj提供的实用方法,用命令行参数调用lua文件(这个 http://lua-users.org/wiki/SourceCodeFormatter

Globals globals = JsePlatform.standardGlobals();
String script ="src/codeformatter.lua";
File f = new File(script);
LuaValue chunk = globals.loadfile(f.getCanonicalPath());
List<String> argList = Arrays.asList("--file","test.lua");
JsePlatform.luaMain(chunk, argList.toArray(new String[argList.size()]));

然而,当代码尝试访问arg表(while i < table.getn(arg) do)时,我总是得到“尝试调用nil”的错误-我尝试了其他例子,它们都导致相同的错误-luaj似乎不能正确设置“arg”表-甚至简单的打印arg[1]也不起作用。

点赞
用户656250
用户656250

LuaJ不再支持table.getn,因为它在lua 5.1中已被删除-用#varname替换table.getn的每个出现-在顶部使用local args={...}初始化args数组使其工作。

然而,代码格式化程序并没有真正做我期望它做的事情。

2015-11-29 19:07:26
用户2556943
用户2556943

有两个问题:

  • table.getn(arg) 的调用应被替换为 #arg
  • 由于 luaj 3.0.1 没有正确设置代码块的环境,因此 arg 没有被设置

然而,作为一种解决方法,你可以使用可变参数 "..." 语法来捕获输入,只需在 codeformatter.lua 的顶部添加一行代码:

arg = {...}

以下是一个示例代码片段:

Globals globals = JsePlatform.standardGlobals();
LuaValue chunk = globals.load(
        "arg = {...};" +
        "print(#arg, arg[1], arg[2])");
JsePlatform.luaMain(chunk, new String[] {"--file","test.lua"});

运行结果如下:

2   --file  test.lua
2016-01-23 17:00:43