简体   繁体   English

使用luaj将参数传递给lua函数

[英]Passing arguments to a lua function with luaj

I'm trying to call a lua function in a Java program using LuaJ. 我正在尝试使用LuaJ在Java程序中调用lua函数。 It works fine when I'm not passing any arguments to the closure: 当我没有向闭包传递任何参数时,它工作正常:

String script = "print 'Hello World!'";
InputStream input = new ByteArrayInputStream(script.getBytes());
Prototype prototype = LuaC.compile(input, "script");
LuaValue globals = JsePlatform.standardGlobals();
LuaClosure closure = new LuaClosure(prototype, globals);
closure.call();

But now I'm trying a lua script with a top-level function that takes an argument and I just can't figure out how to pass in the argument from Java. 但是现在我正在尝试一个带有顶级函数的lua脚本,该函数接受一个参数而我无法弄清楚如何从Java中传入参数。 Here's what I got so far: 这是我到目前为止所得到的:

String script = "function something(argument)\n"+
                            "test_string = 'Hello World!'\n"+
                            "print(test_string)\n"+
                            "print(argument)\n"+
                "end";

InputStream input = new ByteArrayInputStream(script.getBytes());
Prototype prototype = LuaC.compile(input, "script");
LuaValue globals = JsePlatform.standardGlobals();
LuaClosure closure = new LuaClosure(prototype, globals);
closure.invokemethod("something", CoerceJavaToLua.coerce("Foo"));

This results in an Exception on the invokemethod line: 这会导致invoke方法行出现异常:

org.luaj.vm2.LuaError: attempt to index ? org.luaj.vm2.LuaError:尝试索引? (a function value) (函数值)

Thanks for your help! 谢谢你的帮助!

In lua, the top-level scope is an anonymous function with variable arguments. 在lua中,顶级作用域是具有可变参数的匿名函数。 These are accessed using ... In your example, you don't need the function named something, the chunk itself can be used as an unnamed function. 这些是使用...访问的。在您的示例中,您不需要名为something的函数,块本身可以用作未命名的函数。

For example, this code in luaj-3.0-beta1 例如,这个代码在luaj-3.0-beta1中

String script = "argument = ...\n"+
 "test_string = 'Hello World!'\n"+
 "print(test_string)\n"+
 "print(argument)\n";

Globals globals = JsePlatform.standardGlobals();
LuaValue chunk = globals.loadString(script, "myscript");
chunk.call( LuaValue.valueOf("some-arg-value") );

Produced this result for me: 为我制作了这个结果:

Hello World!
some-arg-value

You can pass in any number of arguments this way. 您可以通过这种方式传递任意数量的参数。

Since you receive 既然你收到了

org.luaj.vm2.LuaError: attempt to index ? org.luaj.vm2.LuaError:尝试索引? (a function value) (函数值)

as your error; 作为你的错误; this means that your function is not being created at all. 这意味着您的功能根本没有创建。

Try it without \\n and give spaces in the variable script . 不用\\n尝试它并在变量script给出空格。 Like this: 像这样:

String script = "function something(argument) " + 
        " test_string = 'Hello World!'; " + 
        " print( test_string ); " + 
        " print( argument ); " + 
        " end";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM