From e9ee95fd58d1c3211ed208eba6b8c51cb35aa6e8 Mon Sep 17 00:00:00 2001 From: James Roseborough Date: Sun, 9 Mar 2014 17:59:25 +0000 Subject: [PATCH] Autoflush and encode written bytes in script contexts (fixes issue #20) --- src/jse/org/luaj/vm2/script/LuajContext.java | 16 ++++++++++++-- .../luaj/vm2/script/ScriptEngineTests.java | 21 +++++++++++++++++++ 2 files changed, 35 insertions(+), 2 deletions(-) diff --git a/src/jse/org/luaj/vm2/script/LuajContext.java b/src/jse/org/luaj/vm2/script/LuajContext.java index 7d9393d5..4668e41c 100644 --- a/src/jse/org/luaj/vm2/script/LuajContext.java +++ b/src/jse/org/luaj/vm2/script/LuajContext.java @@ -106,7 +106,7 @@ public class LuajContext extends SimpleScriptContext implements ScriptContext { @Override public void setWriter(Writer writer) { globals.STDOUT = writer != null? - new PrintStream(new WriterOutputStream(writer)): + new PrintStream(new WriterOutputStream(writer), true): stdout; } @@ -116,7 +116,19 @@ public class LuajContext extends SimpleScriptContext implements ScriptContext { this.w = w; } public void write(int b) throws IOException { - w.write(b); + w.write(new String(new byte[] {(byte)b})); + } + public void write(byte[] b, int o, int l) throws IOException { + w.write(new String(b, o, l)); + } + public void write(byte[] b) throws IOException { + w.write(new String(b)); + } + public void close() throws IOException { + w.close(); + } + public void flush() throws IOException { + w.flush(); } } diff --git a/test/junit/org/luaj/vm2/script/ScriptEngineTests.java b/test/junit/org/luaj/vm2/script/ScriptEngineTests.java index 938be766..0756f701 100644 --- a/test/junit/org/luaj/vm2/script/ScriptEngineTests.java +++ b/test/junit/org/luaj/vm2/script/ScriptEngineTests.java @@ -51,6 +51,7 @@ public class ScriptEngineTests extends TestSuite { suite.addTest( new TestSuite( DefaultBindingsTest.class, "Default Bindings" ) ); suite.addTest( new TestSuite( LuaJCBindingsTest.class, "LuaJC Bindings" ) ); suite.addTest( new TestSuite( UserContextTest.class, "User Context" ) ); + suite.addTest( new TestSuite( WriterTest.class, "Writer" ) ); return suite; } @@ -282,4 +283,24 @@ public class ScriptEngineTests extends TestSuite { assertEquals(5, b.get("z")); } } + + public static class WriterTest extends TestCase { + protected ScriptEngine e; + protected Bindings b; + public void setUp() { + this.e = new ScriptEngineManager().getEngineByName("luaj"); + this.b = e.getBindings(ScriptContext.ENGINE_SCOPE); + } + public void testWriter() throws ScriptException { + CharArrayWriter output = new CharArrayWriter(); + CharArrayWriter errors = new CharArrayWriter(); + e.getContext().setWriter(output); + e.getContext().setErrorWriter(errors); + e.eval("io.write( [[line]] )"); + assertEquals("line", output.toString()); + e.eval("io.write( [[ one\nline two\n]] )"); + assertEquals("line one\nline two\n", output.toString()); + output.reset(); + } + } }