加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-14 19:33:28 所属栏目:Java 来源:网络整理
导读:我正在尝试使用LuaJ在 Java程序中调用lua函数.当我没有向闭包传递任何参数时,它工作正常: String script = "print 'Hello World!'";InputStream input = new ByteArrayInputStream(script.getBytes());Prototype prototype = LuaC.compile(input,"script");
我正在尝试使用LuaJ在 Java程序中调用lua函数.当我没有向闭包传递任何参数时,它工作正常:
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();

但是现在我正在尝试一个带有顶级函数的lua脚本,该函数接受一个参数而我无法弄清楚如何从Java中传入参数.这是我到目前为止所得到的:

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,globals);
closure.invokemethod("something",CoerceJavaToLua.coerce("Foo"));

这会导致invoke方法行出现异常:

org.luaj.vm2.LuaError: attempt to index ? (a function value)

谢谢你的帮助!

解决方法

在lua中,顶级作用域是具有可变参数的匿名函数.这些是使用…访问的.在您的示例中,您不需要名为something的函数,块本身可以用作未命名的函数.

例如,这个代码在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") );

为我制作了这个结果:

Hello World!
some-arg-value

您可以通过这种方式传递任意数量的参数.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读