Getting print calls in LuaJ

782 Views Asked by At

I'm writing a Java program which uses Lua scripts to determine what to output to certain areas of the program. Currently, my code looks as such:

Globals globals = JsePlatform.standardGlobals();
LuaValue chunk = globals.loadfile(dir.getAbsolutePath() + "/" + name);
chunk.call();
String output = chunk.tojstring();

The problem is that calling tojstring() appears to return return values from the Lua script. This is fine, but I need to get print calls, as that's what will be displayed on the screen. As of now, the print calls get sent directly to the Console (printed to console), and I cannot figure out a way to retrieve these print calls.

I've tried digging through the documentation but have had little success. Will change from LuaJ if needed.

2

There are 2 best solutions below

0
On BEST ANSWER

I actually was able to solve the problem by changing the STDOUT variable in the globals object to a temporary file, and then reading the data from the temporary file.

Probably not the best solution, but works perfectly fine.

0
On

Expanding on Joseph Boyle's answer (a few years later): You can also set up a printStream to a ByteArrayOutputStream (no need to do it to a file on disk) if that's your poison. I did this in a JUnit test with LuaJ and it works:

  @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"));
  }