我正在编写一个Java程序,它使用Lua脚本来确定输出到程序某些区域的内容。目前,我的代码看起来像这样:
Globals globals = JsePlatform.standardGlobals();
LuaValue chunk = globals.loadfile(dir.getAbsolutePath() + "/" + name);
chunk.call();
String output = chunk.tojstring();
问题是调用tojstring()
似乎从Lua脚本返回return
值。这很好,但我需要print
次呼叫,因为这将是屏幕上显示的内容。截至目前,print
调用已直接发送到控制台(打印到控制台),我无法找到检索这些打印调用的方法。
我尝试过挖掘文档,但收效甚微。如果需要,会改变LuaJ。
答案 0 :(得分:1)
我实际上能够通过将STDOUT
对象中的globals
变量更改为临时文件,然后从临时文件中读取数据来解决问题。
可能不是最好的解决方案,但效果非常好。
答案 1 :(得分:1)
扩展Joseph Boyle的答案(几年后):你也可以将一个printStream设置为ByteArrayOutputStream(无需对磁盘上的文件执行),如果这是你的毒药。我在LuaJ的JUnit测试中做到了这一点并且有效:
@Test
public void testPrintToStringFromLuaj() throws IOException {
String PRINT_HELLO = "print (\"hello world\")";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream printStream = new PrintStream(baos, true, "utf-8");
Globals globals = JsePlatform.standardGlobals();
globals.STDOUT = printStream;
LuaValue load = globals.load(PRINT_HELLO);
load.call();
String content = new String(baos.toByteArray(), StandardCharsets.UTF_8);
printStream.close();
assertThat(content, is("hello world\n"));
}