From 5da65f7d419a3e44c9dd90a0531889ac87b42190 Mon Sep 17 00:00:00 2001 From: James Roseborough Date: Wed, 23 Jul 2008 21:08:09 +0000 Subject: [PATCH] Add test for combination of print() and tostring(), test case when tostring is changed in global environment. --- src/core/org/luaj/lib/BaseLib.java | 9 ++++++- src/core/org/luaj/vm/LValue.java | 5 +++- .../java/org/luaj/vm/CompatibiltyTest.java | 4 +++ src/test/res/print.lua | 26 +++++++++++++++++++ 4 files changed, 42 insertions(+), 2 deletions(-) create mode 100644 src/test/res/print.lua diff --git a/src/core/org/luaj/lib/BaseLib.java b/src/core/org/luaj/lib/BaseLib.java index 9e0c517d..d00032f1 100644 --- a/src/core/org/luaj/lib/BaseLib.java +++ b/src/core/org/luaj/lib/BaseLib.java @@ -122,10 +122,17 @@ public class BaseLib extends LFunction { switch ( id ) { case PRINT: { int n = vm.gettop(); + vm.getglobal("tostring"); for ( int i=2; i<=n; i++ ) { + vm.pushvalue(-1); + vm.pushvalue(i); + vm.call(1, 1); + if ( vm.type(-1) != Lua.LUA_TSTRING ) + vm.error( "'tostring' must return a string to 'print'" ); if ( i > 2 ) STDOUT.print( "\t" ); - STDOUT.print( vm.tostring(i) ); + STDOUT.print( vm.tostring(-1) ); + vm.poplvalue(); } STDOUT.println(); vm.resettop(); diff --git a/src/core/org/luaj/vm/LValue.java b/src/core/org/luaj/vm/LValue.java index 652e7974..f83d6eb2 100644 --- a/src/core/org/luaj/vm/LValue.java +++ b/src/core/org/luaj/vm/LValue.java @@ -321,7 +321,10 @@ public class LValue { baos.write(b,0,b.length); } - /** Return true if this is a LString */ + /** Return true if this is a lua string, meaning it is + * either a LString or LNumber,since all numbers are + * convertible to strings in lua + */ public boolean isString() { return false; } diff --git a/src/test/java/org/luaj/vm/CompatibiltyTest.java b/src/test/java/org/luaj/vm/CompatibiltyTest.java index 4d15c8e1..fd8f8ced 100644 --- a/src/test/java/org/luaj/vm/CompatibiltyTest.java +++ b/src/test/java/org/luaj/vm/CompatibiltyTest.java @@ -112,6 +112,10 @@ public class CompatibiltyTest extends ScriptDrivenTest { runTest("pcalls"); } + public void testPrint() throws IOException, InterruptedException { + runTest("print"); + } + public void testRequire() throws IOException, InterruptedException { runTest("require"); } diff --git a/src/test/res/print.lua b/src/test/res/print.lua new file mode 100644 index 00000000..664ecd5b --- /dev/null +++ b/src/test/res/print.lua @@ -0,0 +1,26 @@ +-- print uses tostring under-the-hood! + +local function f() + print() + print('abc') + print(123) + print(true) + print('abc',123,true) +end + +local function g() + local fenv = {tostring=function(x) + return '*'..type(x)..'*' + end} + package.seeall(fenv) + f() + print('setfenv', pcall(setfenv, 0, fenv), {}, f ) + f() +end + +local s,c = pcall( coroutine.create, g ) +print('create', s, s and type(c) or c) +print('resume', pcall( coroutine.resume, c ) ) +f() + +