【问题标题】:Getting print calls in LuaJ在 LuaJ 中获取打印调用
【发布时间】:2015-01-27 12:27:11
【问题描述】:

我正在编写一个 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 更改。

【问题讨论】:

    标签: java lua luaj


    【解决方案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"));
      }
    

    【讨论】:

      【解决方案2】:

      我实际上是通过将globals对象中的STDOUT变量更改为临时文件,然后从临时文件中读取数据来解决问题的。

      可能不是最好的解决方案,但效果很好。

      【讨论】:

        猜你喜欢
        • 2019-08-14
        • 2019-01-16
        • 2016-04-12
        • 1970-01-01
        • 2022-12-14
        • 1970-01-01
        • 1970-01-01
        • 2012-06-30
        • 1970-01-01
        相关资源
        最近更新 更多