我正在编写一个 Java 程序,它使用 Lua 脚本来确定要输出到程序的某些区域的内容。目前,我的代码如下所示:
Globals globals = JsePlatform.standardGlobals();
LuaValue chunk = globals.loadfile(dir.getAbsolutePath() + "/" + name);
chunk.call();
String output = chunk.tojstring();
Run Code Online (Sandbox Code Playgroud)
问题是调用似乎从 Lua 脚本tojstring()返回值。return这很好,但我需要接听print电话,因为这就是屏幕上显示的内容。截至目前,print调用直接发送到控制台(打印到控制台),并且我无法找到检索这些打印调用的方法。
我尝试过深入研究文档,但收效甚微。如果需要的话将从 LuaJ 进行更改。
扩展 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"));
}
Run Code Online (Sandbox Code Playgroud)