Add formatter definition and format code

This commit is contained in:
Enrico Horn
2021-07-03 22:23:09 +02:00
parent 3c266bcc98
commit e7e6190f9c
144 changed files with 17201 additions and 14311 deletions

View File

@@ -8,43 +8,43 @@ import org.luaj.vm2.lib.VarArgFunction;
public class SampleMainChunk extends VarArgFunction {
static final LuaValue $print = valueOf("print");
static final LuaValue $foo = valueOf("foo");
LuaValue[] rw_ENV; // The environment when it is read-write
static final LuaValue $foo = valueOf("foo");
LuaValue[] rw_ENV; // The environment when it is read-write
// LuaValue ro_ENV; // The environment when it is read-only in all sub-functions
LuaValue[] rw_openup1; // upvalue that we create and modify in "slot" 1, passed to sub-function in initer.
LuaValue[] rw_openup2; // array is instantiated on first set or before supply to closure, after that value is get, set.
LuaValue[] rw_openup3; // closing these nulls them out, sub-functions still retain references to array & can use
LuaValue ro_openup4; // open upvalue that is read-only once it is supplied to an inner function.
LuaValue ro_openup5; // closing this also nulls it out.
LuaValue[] rw_openup1; // upvalue that we create and modify in "slot" 1, passed to sub-function in initer.
LuaValue[] rw_openup2; // array is instantiated on first set or before supply to closure, after that value is get, set.
LuaValue[] rw_openup3; // closing these nulls them out, sub-functions still retain references to array & can use
LuaValue ro_openup4; // open upvalue that is read-only once it is supplied to an inner function.
LuaValue ro_openup5; // closing this also nulls it out.
// Must have this in the main chunk so it can be loaded and instantiated on all platforms.
public SampleMainChunk() {
}
public void initupvalue1(LuaValue[] v) {
this.rw_ENV = v;
}
public Varargs invoke(Varargs args) {
rw_ENV[0].get($print).call($foo);
rw_ENV[0].set($print, new InnerFunction(rw_openup3, rw_openup1, ro_openup5));
return null;
}
static class InnerFunction extends TwoArgFunction {
static final LuaValue $print = valueOf("print"); // A constant, named for what it is.
static final LuaValue $foo = valueOf("foo");
final LuaValue[] rw_upvalue1; // from enclosing function, corresponds to upvaldesc not instack.
final LuaValue[] rw_upvalue2; // from enclosing function, corresponds to upvaldesc not instack.
final LuaValue ro_upvalue3; // from enclosing function, but read-only everywhere.
static final LuaValue $foo = valueOf("foo");
LuaValue[] rw_openup1; // closing these nulls them out, sub-functions still retain references to array & can use
LuaValue ro_openup2; // open upvalue that is read-only once it is supplied to an inner function.
final LuaValue[] rw_upvalue1; // from enclosing function, corresponds to upvaldesc not instack.
final LuaValue[] rw_upvalue2; // from enclosing function, corresponds to upvaldesc not instack.
final LuaValue ro_upvalue3; // from enclosing function, but read-only everywhere.
LuaValue[] rw_openup1; // closing these nulls them out, sub-functions still retain references to array & can use
LuaValue ro_openup2; // open upvalue that is read-only once it is supplied to an inner function.
InnerFunction(LuaValue[] rw_upvalue1, LuaValue[] rw_upvalue2, LuaValue ro_upvalue3) {
this.rw_upvalue1 = rw_upvalue1;
@@ -55,7 +55,7 @@ public class SampleMainChunk extends VarArgFunction {
public LuaValue call(LuaValue arg1, LuaValue arg2) {
return NIL;
}
}
}

View File

@@ -30,41 +30,33 @@ import org.luaj.vm2.lib.jse.JsePlatform;
/** Test the plain old bytecode interpreter */
public class TestLuaJ {
// create the script
public static String name = "script";
public static String script =
"function r(q,...)\n"+
" local a=arg\n"+
" return a and a[2]\n"+
"end\n" +
"function s(q,...)\n"+
" local a=arg\n"+
" local b=...\n"+
" return a and a[2],b\n"+
"end\n" +
"print( r(111,222,333),s(111,222,333) )";
public static String name = "script";
public static String script = "function r(q,...)\n" + " local a=arg\n" + " return a and a[2]\n" + "end\n"
+ "function s(q,...)\n" + " local a=arg\n" + " local b=...\n" + " return a and a[2],b\n" + "end\n"
+ "print( r(111,222,333),s(111,222,333) )";
public static void main(String[] args) throws Exception {
System.out.println(script);
// create an environment to run in
Globals globals = JsePlatform.standardGlobals();
// compile into a chunk, or load as a class
LuaValue chunk = globals.load(script, "script");
// The loaded chunk should be a closure, which contains the prototype.
print( chunk.checkclosure().p );
print(chunk.checkclosure().p);
// The chunk can be called with arguments as desired.
chunk.call(LuaValue.ZERO, LuaValue.ONE);
}
private static void print(Prototype p) {
System.out.println("--- "+p);
System.out.println("--- " + p);
Print.printCode(p);
if (p.p!=null)
for ( int i=0,n=p.p.length; i<n; i++ )
print( p.p[i] );
if (p.p != null)
for (int i = 0, n = p.p.length; i < n; i++)
print(p.p[i]);
}
}

View File

@@ -40,13 +40,13 @@ public class TestLuaJC {
public static String filename = "perf/nsieve.lua";
static Globals globals;
public static void main(String[] args) throws Exception {
if (args.length > 0)
filename = args[0];
System.out.println("filename: "+filename);
System.out.println("filename: " + filename);
try {
// create an environment to run in
globals = JsePlatform.standardGlobals();
@@ -56,47 +56,44 @@ public class TestLuaJC {
Print.print(p);
// load into a luajc java-bytecode based chunk by installing the LuaJC compiler first
if ( ! (args.length>0 && args[0].equals("nocompile")) ) {
if (!(args.length > 0 && args[0].equals("nocompile"))) {
LuaJC.install(globals);
f = globals.loadfile(filename).arg1();
}
// call with arguments
Varargs v = f.invoke(LuaValue.NONE);
// print the result
System.out.println("result: "+v);
System.out.println("result: " + v);
// Write out the files.
// saveClasses();
} catch ( Throwable e ) {
} catch (Throwable e) {
e.printStackTrace();
}
}
private static void saveClasses() throws Exception {
// create the chunk
// create the chunk
String destdir = ".";
InputStream is = globals.finder.findResource(filename);
Hashtable t = LuaJC.instance.compileAll(is, filename, filename, globals, true);
// write out the chunk
for ( Enumeration e = t.keys(); e.hasMoreElements(); ) {
String key = (String) e.nextElement();
byte[] bytes = (byte[]) t.get(key);
String destpath = (destdir!=null? destdir+"/": "") + key + ".class";
System.out.println(
"chunk "+filename+
" from "+filename+
" written to "+destpath
+" length="+bytes.length+" bytes");
FileOutputStream fos = new FileOutputStream( destpath );
fos.write( bytes );
fos.close();
}
// write out the chunk
for (Enumeration e = t.keys(); e.hasMoreElements();) {
String key = (String) e.nextElement();
byte[] bytes = (byte[]) t.get(key);
String destpath = (destdir != null? destdir + "/": "") + key + ".class";
System.out.println("chunk " + filename + " from " + filename + " written to " + destpath + " length="
+ bytes.length + " bytes");
FileOutputStream fos = new FileOutputStream(destpath);
fos.write(bytes);
fos.close();
}
}
}

View File

@@ -64,17 +64,17 @@ public class AllTests {
table.addTestSuite(WeakKeyTableTest.class);
table.addTestSuite(WeakKeyValueTableTest.class);
suite.addTest(table);
// bytecode compilers regression tests
TestSuite bytecodetests = FragmentsTest.suite();
suite.addTest(bytecodetests);
// I/O tests
TestSuite io = new TestSuite("I/O Tests");
io.addTestSuite(BufferedStreamTest.class);
io.addTestSuite(UTF8StreamTest.class);
suite.addTest(io);
// prototype compiler
TestSuite compiler = new TestSuite("Lua Compiler Tests");
compiler.addTestSuite(CompilerUnitTests.class);
@@ -83,7 +83,7 @@ public class AllTests {
compiler.addTestSuite(RegressionTests.class);
compiler.addTestSuite(SimpleTests.class);
suite.addTest(compiler);
// library tests
TestSuite lib = new TestSuite("Library Tests");
lib.addTestSuite(JsePlatformTest.class);
@@ -97,12 +97,12 @@ public class AllTests {
// Script engine tests.
TestSuite script = ScriptEngineTests.suite();
suite.addTest(script);
// compatiblity tests
TestSuite compat = CompatibiltyTest.suite();
suite.addTest(compat);
compat.addTestSuite(ErrorsTest.class);
return suite;
}

View File

@@ -27,26 +27,25 @@ import junit.framework.TestCase;
import org.luaj.vm2.Globals.BufferedStream;
public class BufferedStreamTest extends TestCase {
public BufferedStreamTest() {}
private BufferedStream NewBufferedStream(int buflen, String contents) {
return new BufferedStream(buflen, new ByteArrayInputStream(contents.getBytes()));
}
protected void setUp() throws Exception {
super.setUp();
}
public void testReadEmptyStream() throws java.io.IOException {
BufferedStream bs = NewBufferedStream(4, "");
assertEquals(-1, bs.read());
assertEquals(-1, bs.read(new byte[10]));
assertEquals(-1, bs.read(new byte[10], 0, 10));
}
public void testReadByte() throws java.io.IOException {
BufferedStream bs = NewBufferedStream(2, "abc");
assertEquals('a', bs.read());
@@ -54,7 +53,7 @@ public class BufferedStreamTest extends TestCase {
assertEquals('c', bs.read());
assertEquals(-1, bs.read());
}
public void testReadByteArray() throws java.io.IOException {
byte[] array = new byte[3];
BufferedStream bs = NewBufferedStream(4, "abcdef");
@@ -66,7 +65,7 @@ public class BufferedStreamTest extends TestCase {
assertEquals("ef", new String(array, 0, 2));
assertEquals(-1, bs.read());
}
public void testReadByteArrayOffsetLength() throws java.io.IOException {
byte[] array = new byte[10];
BufferedStream bs = NewBufferedStream(8, "abcdefghijklmn");
@@ -78,7 +77,7 @@ public class BufferedStreamTest extends TestCase {
assertEquals("ijklmn", new String(array, 0, 6));
assertEquals(-1, bs.read());
}
public void testMarkOffsetBeginningOfStream() throws java.io.IOException {
byte[] array = new byte[4];
BufferedStream bs = NewBufferedStream(8, "abcdefghijkl");

View File

@@ -28,19 +28,20 @@ import org.luaj.vm2.luajc.LuaJC;
/**
* Compatibility tests for the Luaj VM
*
* Results are compared for exact match with
* the installed C-based lua environment.
* Results are compared for exact match with the installed C-based lua
* environment.
*/
public class CompatibiltyTest extends TestSuite {
private static final String dir = "";
abstract protected static class CompatibiltyTestSuite extends ScriptDrivenTest {
abstract protected static class CompatibiltyTestSuite extends ScriptDrivenTest {
LuaValue savedStringMetatable;
protected CompatibiltyTestSuite(PlatformType platform) {
super(platform,dir);
super(platform, dir);
}
protected void setUp() throws Exception {
savedStringMetatable = LuaString.s_metatable;
super.setUp();
@@ -56,60 +57,79 @@ public class CompatibiltyTest extends TestSuite {
LuaString.s_metatable = savedStringMetatable;
}
public void testBaseLib() { runTest("baselib"); }
public void testCoroutineLib() { runTest("coroutinelib"); }
public void testDebugLib() { runTest("debuglib"); }
public void testErrors() { runTest("errors"); }
public void testFunctions() { runTest("functions"); }
public void testIoLib() { runTest("iolib"); }
public void testManyUpvals() { runTest("manyupvals"); }
public void testMathLib() { runTest("mathlib"); }
public void testMetatags() { runTest("metatags"); }
public void testOsLib() { runTest("oslib"); }
public void testStringLib() { runTest("stringlib"); }
public void testTableLib() { runTest("tablelib"); }
public void testTailcalls() { runTest("tailcalls"); }
public void testUpvalues() { runTest("upvalues"); }
public void testVm() { runTest("vm"); }
}
public void testBaseLib() { runTest("baselib"); }
public void testCoroutineLib() { runTest("coroutinelib"); }
public void testDebugLib() { runTest("debuglib"); }
public void testErrors() { runTest("errors"); }
public void testFunctions() { runTest("functions"); }
public void testIoLib() { runTest("iolib"); }
public void testManyUpvals() { runTest("manyupvals"); }
public void testMathLib() { runTest("mathlib"); }
public void testMetatags() { runTest("metatags"); }
public void testOsLib() { runTest("oslib"); }
public void testStringLib() { runTest("stringlib"); }
public void testTableLib() { runTest("tablelib"); }
public void testTailcalls() { runTest("tailcalls"); }
public void testUpvalues() { runTest("upvalues"); }
public void testVm() { runTest("vm"); }
}
public static TestSuite suite() {
TestSuite suite = new TestSuite("Compatibility Tests");
suite.addTest( new TestSuite( JseCompatibilityTest.class, "JSE Compatibility Tests" ) );
suite.addTest( new TestSuite( JmeCompatibilityTest.class, "JME Compatibility Tests" ) );
suite.addTest( new TestSuite( LuaJCCompatibilityTest.class, "LuaJC Compatibility Tests" ) );
suite.addTest(new TestSuite(JseCompatibilityTest.class, "JSE Compatibility Tests"));
suite.addTest(new TestSuite(JmeCompatibilityTest.class, "JME Compatibility Tests"));
suite.addTest(new TestSuite(LuaJCCompatibilityTest.class, "LuaJC Compatibility Tests"));
return suite;
}
public static class JmeCompatibilityTest extends CompatibiltyTestSuite {
public JmeCompatibilityTest() {
super(ScriptDrivenTest.PlatformType.JME);
}
protected void setUp() throws Exception {
System.setProperty("JME", "true");
super.setUp();
}
}
public static class JseCompatibilityTest extends CompatibiltyTestSuite {
public JseCompatibilityTest() {
super(ScriptDrivenTest.PlatformType.JSE);
}
protected void setUp() throws Exception {
super.setUp();
System.setProperty("JME", "false");
}
}
public static class LuaJCCompatibilityTest extends CompatibiltyTestSuite {
public LuaJCCompatibilityTest() {
super(ScriptDrivenTest.PlatformType.LUAJIT);
}
protected void setUp() throws Exception {
super.setUp();
System.setProperty("JME", "false");
LuaJC.install(globals);
}
// not supported on this platform - don't test
public void testDebugLib() {}
public void testDebugLib() {}
}
}

View File

@@ -24,12 +24,11 @@ package org.luaj.vm2;
import java.io.IOException;
import java.io.InputStream;
/**
* Test argument type check errors
*
* Results are compared for exact match with
* the installed C-based lua environment.
* Results are compared for exact match with the installed C-based lua
* environment.
*/
public class ErrorsTest extends ScriptDrivenTest {
@@ -38,26 +37,34 @@ public class ErrorsTest extends ScriptDrivenTest {
public ErrorsTest() {
super(ScriptDrivenTest.PlatformType.JSE, dir);
}
protected void setUp() throws Exception {
super.setUp();
}
public void testBaseLibArgs() {
public void testBaseLibArgs() {
globals.STDIN = new InputStream() {
public int read() throws IOException {
return -1;
}
};
runTest("baselibargs");
runTest("baselibargs");
}
public void testCoroutineLibArgs() { runTest("coroutinelibargs"); }
public void testDebugLibArgs() { runTest("debuglibargs"); }
public void testIoLibArgs() { runTest("iolibargs"); }
public void testMathLibArgs() { runTest("mathlibargs"); }
public void testModuleLibArgs() { runTest("modulelibargs"); }
public void testOperators() { runTest("operators"); }
public void testStringLibArgs() { runTest("stringlibargs"); }
public void testTableLibArgs() { runTest("tablelibargs"); }
public void testCoroutineLibArgs() { runTest("coroutinelibargs"); }
public void testDebugLibArgs() { runTest("debuglibargs"); }
public void testIoLibArgs() { runTest("iolibargs"); }
public void testMathLibArgs() { runTest("mathlibargs"); }
public void testModuleLibArgs() { runTest("modulelibargs"); }
public void testOperators() { runTest("operators"); }
public void testStringLibArgs() { runTest("stringlibargs"); }
public void testTableLibArgs() { runTest("tablelibargs"); }
}

View File

@@ -30,44 +30,46 @@ import junit.framework.TestSuite;
import org.luaj.vm2.lib.jse.JsePlatform;
import org.luaj.vm2.luajc.LuaJC;
/**
* Test compilation of various fragments that have
* caused problems for jit compiling during development.
/**
* Test compilation of various fragments that have caused problems for jit
* compiling during development.
*
*/
public class FragmentsTest extends TestSuite {
static final int TEST_TYPE_LUAC = 0;
static final int TEST_TYPE_LUAJC = 1;
static final int TEST_TYPE_LUAC = 0;
static final int TEST_TYPE_LUAJC = 1;
public static class JseFragmentsTest extends FragmentsTestCase {
public JseFragmentsTest() { super( TEST_TYPE_LUAC ); }
public JseFragmentsTest() { super(TEST_TYPE_LUAC); }
}
public static class LuaJCFragmentsTest extends FragmentsTestCase {
public LuaJCFragmentsTest() { super( TEST_TYPE_LUAJC ); }
public LuaJCFragmentsTest() { super(TEST_TYPE_LUAJC); }
}
public static TestSuite suite() {
TestSuite suite = new TestSuite("Compiler Fragments Tests");
suite.addTest( new TestSuite( JseFragmentsTest.class, "JSE Fragments Tests" ) );
suite.addTest( new TestSuite( LuaJCFragmentsTest.class, "LuaJC Fragments Tests" ) );
suite.addTest(new TestSuite(JseFragmentsTest.class, "JSE Fragments Tests"));
suite.addTest(new TestSuite(LuaJCFragmentsTest.class, "LuaJC Fragments Tests"));
return suite;
}
abstract protected static class FragmentsTestCase extends TestCase {
abstract protected static class FragmentsTestCase extends TestCase {
final int TEST_TYPE;
protected FragmentsTestCase(int testType) {
this.TEST_TYPE = testType;
}
public void runFragment( Varargs expected, String script ) {
public void runFragment(Varargs expected, String script) {
try {
String name = getName();
Globals globals = JsePlatform.debugGlobals();
Reader reader = new StringReader(script);
LuaValue chunk ;
switch ( TEST_TYPE ) {
LuaValue chunk;
switch (TEST_TYPE) {
case TEST_TYPE_LUAJC:
LuaJC.install(globals);
chunk = globals.load(reader, name);
@@ -79,534 +81,321 @@ public class FragmentsTest extends TestSuite {
break;
}
Varargs actual = chunk.invoke();
assertEquals( expected.narg(), actual.narg() );
for ( int i=1; i<=actual.narg(); i++ )
assertEquals( expected.arg(i), actual.arg(i) );
assertEquals(expected.narg(), actual.narg());
for (int i = 1; i <= actual.narg(); i++)
assertEquals(expected.arg(i), actual.arg(i));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
fail(e.toString());
}
}
}
public void testFirstArgNilExtended() {
runFragment( LuaValue.NIL,
"function f1(a) print( 'f1:', a ) return a end\n" +
"b = f1()\n" +
"return b" );
runFragment(LuaValue.NIL, "function f1(a) print( 'f1:', a ) return a end\n" + "b = f1()\n" + "return b");
}
public void testSimpleForloop() {
runFragment( LuaValue.valueOf(77),
"for n,p in ipairs({77}) do\n"+
" print('n,p',n,p)\n"+
" return p\n"+
"end\n");
runFragment(LuaValue.valueOf(77),
"for n,p in ipairs({77}) do\n" + " print('n,p',n,p)\n" + " return p\n" + "end\n");
}
public void testForloopParamUpvalues() {
runFragment( LuaValue.varargsOf(new LuaValue[] {
LuaValue.valueOf(77),
LuaValue.valueOf(1) } ),
"for n,p in ipairs({77}) do\n"+
" print('n,p',n,p)\n"+
" foo = function()\n"+
" return p,n\n"+
" end\n"+
" return foo()\n"+
"end\n");
runFragment(LuaValue.varargsOf(new LuaValue[] { LuaValue.valueOf(77), LuaValue.valueOf(1) }),
"for n,p in ipairs({77}) do\n" + " print('n,p',n,p)\n" + " foo = function()\n" + " return p,n\n"
+ " end\n" + " return foo()\n" + "end\n");
}
public void testArgVarargsUseBoth() {
runFragment( LuaValue.varargsOf( new LuaValue[] {
LuaValue.valueOf("a"),
LuaValue.valueOf("b"),
LuaValue.valueOf("c")}),
"function v(arg,...)\n" +
" return arg,...\n" +
"end\n" +
"return v('a','b','c')\n" );
runFragment(
LuaValue
.varargsOf(new LuaValue[] { LuaValue.valueOf("a"), LuaValue.valueOf("b"), LuaValue.valueOf("c") }),
"function v(arg,...)\n" + " return arg,...\n" + "end\n" + "return v('a','b','c')\n");
}
public void testArgParamUseNone() {
runFragment( LuaValue.valueOf("string"),
"function v(arg,...)\n" +
" return type(arg)\n" +
"end\n" +
"return v('abc')\n" );
runFragment(LuaValue.valueOf("string"),
"function v(arg,...)\n" + " return type(arg)\n" + "end\n" + "return v('abc')\n");
}
public void testSetlistVarargs() {
runFragment( LuaValue.valueOf("abc"),
"local f = function() return 'abc' end\n" +
"local g = { f() }\n" +
"return g[1]\n" );
runFragment(LuaValue.valueOf("abc"),
"local f = function() return 'abc' end\n" + "local g = { f() }\n" + "return g[1]\n");
}
public void testSelfOp() {
runFragment( LuaValue.valueOf("bcd"),
"local s = 'abcde'\n"+
"return s:sub(2,4)\n" );
runFragment(LuaValue.valueOf("bcd"), "local s = 'abcde'\n" + "return s:sub(2,4)\n");
}
public void testSetListWithOffsetAndVarargs() {
runFragment( LuaValue.valueOf(1003),
"local bar = {1000, math.sqrt(9)}\n"+
"return bar[1]+bar[2]\n" );
runFragment(LuaValue.valueOf(1003), "local bar = {1000, math.sqrt(9)}\n" + "return bar[1]+bar[2]\n");
}
public void testMultiAssign() {
// arargs evaluations are all done before assignments
runFragment( LuaValue.varargsOf(new LuaValue[]{
LuaValue.valueOf(111),
LuaValue.valueOf(111),
LuaValue.valueOf(111)}),
"a,b,c = 1,10,100\n" +
"a,b,c = a+b+c, a+b+c, a+b+c\n" +
"return a,b,c\n" );
runFragment(
LuaValue
.varargsOf(new LuaValue[] { LuaValue.valueOf(111), LuaValue.valueOf(111), LuaValue.valueOf(111) }),
"a,b,c = 1,10,100\n" + "a,b,c = a+b+c, a+b+c, a+b+c\n" + "return a,b,c\n");
}
public void testUpvalues() {
runFragment( LuaValue.valueOf(999),
"local a = function(x)\n" +
" return function(y)\n" +
" return x + y\n" +
" end\n" +
"end\n" +
"local b = a(222)\n" +
"local c = b(777)\n" +
"print( 'c=', c )\n" +
"return c\n" );
runFragment(LuaValue.valueOf(999),
"local a = function(x)\n" + " return function(y)\n" + " return x + y\n" + " end\n" + "end\n"
+ "local b = a(222)\n" + "local c = b(777)\n" + "print( 'c=', c )\n" + "return c\n");
}
public void testNonAsciiStringLiterals() {
runFragment( LuaValue.valueOf("7,8,12,10,9,11,133,222"),
"local a='\\a\\b\\f\\n\\t\\v\\133\\222'\n"+
"local t={string.byte(a,1,#a)}\n"+
"return table.concat(t,',')\n" );
runFragment(LuaValue.valueOf("7,8,12,10,9,11,133,222"), "local a='\\a\\b\\f\\n\\t\\v\\133\\222'\n"
+ "local t={string.byte(a,1,#a)}\n" + "return table.concat(t,',')\n");
}
public void testControlCharStringLiterals() {
runFragment( LuaValue.valueOf("97,0,98,18,99,18,100,18,48,101"),
"local a='a\\0b\\18c\\018d\\0180e'\n"+
"local t={string.byte(a,1,#a)}\n"+
"return table.concat(t,',')\n" );
runFragment(LuaValue.valueOf("97,0,98,18,99,18,100,18,48,101"), "local a='a\\0b\\18c\\018d\\0180e'\n"
+ "local t={string.byte(a,1,#a)}\n" + "return table.concat(t,',')\n");
}
public void testLoopVarNames() {
runFragment( LuaValue.valueOf(" 234,1,aa 234,2,bb"),
"local w = ''\n"+
"function t()\n"+
" for f,var in ipairs({'aa','bb'}) do\n"+
" local s = 234\n"+
" w = w..' '..s..','..f..','..var\n"+
" end\n"+
"end\n" +
"t()\n" +
"return w\n" );
runFragment(LuaValue.valueOf(" 234,1,aa 234,2,bb"),
"local w = ''\n" + "function t()\n" + " for f,var in ipairs({'aa','bb'}) do\n" + " local s = 234\n"
+ " w = w..' '..s..','..f..','..var\n" + " end\n" + "end\n" + "t()\n" + "return w\n");
}
public void testForLoops() {
runFragment( LuaValue.valueOf("12345 357 963"),
"local s,t,u = '','',''\n"+
"for m=1,5 do\n"+
" s = s..m\n"+
"end\n"+
"for m=3,7,2 do\n"+
" t = t..m\n"+
"end\n"+
"for m=9,3,-3 do\n"+
" u = u..m\n"+
"end\n"+
"return s..' '..t..' '..u\n" );
runFragment(LuaValue.valueOf("12345 357 963"),
"local s,t,u = '','',''\n" + "for m=1,5 do\n" + " s = s..m\n" + "end\n" + "for m=3,7,2 do\n"
+ " t = t..m\n" + "end\n" + "for m=9,3,-3 do\n" + " u = u..m\n" + "end\n"
+ "return s..' '..t..' '..u\n");
}
public void testLocalFunctionDeclarations() {
runFragment( LuaValue.varargsOf(LuaValue.valueOf("function"),LuaValue.valueOf("nil")),
"local function aaa()\n"+
" return type(aaa)\n"+
"end\n"+
"local bbb = function()\n"+
" return type(bbb)\n"+
"end\n"+
"return aaa(),bbb()\n" );
runFragment(LuaValue.varargsOf(LuaValue.valueOf("function"), LuaValue.valueOf("nil")),
"local function aaa()\n" + " return type(aaa)\n" + "end\n" + "local bbb = function()\n"
+ " return type(bbb)\n" + "end\n" + "return aaa(),bbb()\n");
}
public void testNilsInTableConstructor() {
runFragment( LuaValue.valueOf("1=111 2=222 3=333 "),
"local t = { 111, 222, 333, nil, nil }\n"+
"local s = ''\n"+
"for i,v in ipairs(t) do \n" +
" s=s..tostring(i)..'='..tostring(v)..' '\n" +
"end\n"+
"return s\n" );
runFragment(LuaValue.valueOf("1=111 2=222 3=333 "),
"local t = { 111, 222, 333, nil, nil }\n" + "local s = ''\n" + "for i,v in ipairs(t) do \n"
+ " s=s..tostring(i)..'='..tostring(v)..' '\n" + "end\n" + "return s\n");
}
public void testUnreachableCode() {
runFragment( LuaValue.valueOf(66),
"local function foo(x) return x * 2 end\n" +
"local function bar(x, y)\n" +
" if x==y then\n" +
" return y\n" +
" else\n" +
" return foo(x)\n" +
" end\n" +
"end\n" +
"return bar(33,44)\n" );
runFragment(LuaValue.valueOf(66),
"local function foo(x) return x * 2 end\n" + "local function bar(x, y)\n" + " if x==y then\n"
+ " return y\n" + " else\n" + " return foo(x)\n" + " end\n" + "end\n"
+ "return bar(33,44)\n");
}
public void testVarargsWithParameters() {
runFragment( LuaValue.valueOf(222),
"local func = function(t,...)\n"+
" return (...)\n"+
"end\n"+
"return func(111,222,333)\n" );
runFragment(LuaValue.valueOf(222),
"local func = function(t,...)\n" + " return (...)\n" + "end\n" + "return func(111,222,333)\n");
}
public void testNoReturnValuesPlainCall() {
runFragment( LuaValue.TRUE,
"local testtable = {}\n"+
"return pcall( function() testtable[1]=2 end )\n" );
runFragment(LuaValue.TRUE, "local testtable = {}\n" + "return pcall( function() testtable[1]=2 end )\n");
}
public void testVarargsInTableConstructor() {
runFragment( LuaValue.valueOf(222),
"local function foo() return 111,222,333 end\n"+
"local t = {'a','b',c='c',foo()}\n"+
"return t[4]\n" );
runFragment(LuaValue.valueOf(222), "local function foo() return 111,222,333 end\n"
+ "local t = {'a','b',c='c',foo()}\n" + "return t[4]\n");
}
public void testVarargsInFirstArg() {
runFragment( LuaValue.valueOf(123),
"function aaa(x) return x end\n" +
"function bbb(y) return y end\n" +
"function ccc(z) return z end\n" +
"return ccc( aaa(bbb(123)), aaa(456) )\n" );
runFragment(LuaValue.valueOf(123), "function aaa(x) return x end\n" + "function bbb(y) return y end\n"
+ "function ccc(z) return z end\n" + "return ccc( aaa(bbb(123)), aaa(456) )\n");
}
public void testSetUpvalueTableInitializer() {
runFragment( LuaValue.valueOf("b"),
"local aliases = {a='b'}\n" +
"local foo = function()\n" +
" return aliases\n" +
"end\n" +
"return foo().a\n" );
runFragment(LuaValue.valueOf("b"), "local aliases = {a='b'}\n" + "local foo = function()\n"
+ " return aliases\n" + "end\n" + "return foo().a\n");
}
public void testLoadNilUpvalue() {
runFragment( LuaValue.NIL,
"tostring = function() end\n" +
"local pc \n" +
"local pcall = function(...)\n" +
" pc(...)\n" +
"end\n" +
"return NIL\n" );
runFragment(LuaValue.NIL, "tostring = function() end\n" + "local pc \n" + "local pcall = function(...)\n"
+ " pc(...)\n" + "end\n" + "return NIL\n");
}
public void testUpvalueClosure() {
runFragment( LuaValue.NIL,
"print()\n"+
"local function f2() end\n"+
"local function f3()\n"+
" return f3\n"+
"end\n" +
"return NIL\n" );
runFragment(LuaValue.NIL, "print()\n" + "local function f2() end\n" + "local function f3()\n"
+ " return f3\n" + "end\n" + "return NIL\n");
}
public void testUninitializedUpvalue() {
runFragment( LuaValue.NIL,
"local f\n"+
"do\n"+
" function g()\n"+
" print(f())\n"+
" end\n"+
"end\n" +
"return NIL\n" );
runFragment(LuaValue.NIL, "local f\n" + "do\n" + " function g()\n" + " print(f())\n" + " end\n"
+ "end\n" + "return NIL\n");
}
public void testTestOpUpvalues() {
runFragment( LuaValue.varargsOf(LuaValue.valueOf(1),LuaValue.valueOf(2),LuaValue.valueOf(3)),
"print( nil and 'T' or 'F' )\n"+
"local a,b,c = 1,2,3\n"+
"function foo()\n"+
" return a,b,c\n"+
"end\n" +
"return foo()\n" );
runFragment(LuaValue.varargsOf(LuaValue.valueOf(1), LuaValue.valueOf(2), LuaValue.valueOf(3)),
"print( nil and 'T' or 'F' )\n" + "local a,b,c = 1,2,3\n" + "function foo()\n" + " return a,b,c\n"
+ "end\n" + "return foo()\n");
}
public void testTestSimpleBinops() {
runFragment( LuaValue.varargsOf(new LuaValue[] {
LuaValue.FALSE, LuaValue.FALSE, LuaValue.TRUE, LuaValue.TRUE, LuaValue.FALSE }),
"local a,b,c = 2,-2.5,0\n" +
"return (a==c), (b==c), (a==a), (a>c), (b>0)\n" );
runFragment(
LuaValue.varargsOf(
new LuaValue[] { LuaValue.FALSE, LuaValue.FALSE, LuaValue.TRUE, LuaValue.TRUE, LuaValue.FALSE }),
"local a,b,c = 2,-2.5,0\n" + "return (a==c), (b==c), (a==a), (a>c), (b>0)\n");
}
public void testNumericForUpvalues() {
runFragment( LuaValue.valueOf(8),
"for i = 3,4 do\n"+
" i = i + 5\n"+
" local a = function()\n"+
" return i\n"+
" end\n" +
" return a()\n"+
"end\n");
runFragment(LuaValue.valueOf(8), "for i = 3,4 do\n" + " i = i + 5\n" + " local a = function()\n"
+ " return i\n" + " end\n" + " return a()\n" + "end\n");
}
public void testNumericForUpvalues2() {
runFragment( LuaValue.valueOf("222 222"),
"local t = {}\n"+
"local template = [[123 456]]\n"+
"for i = 1,2 do\n"+
" t[i] = template:gsub('%d', function(s)\n"+
" return i\n"+
" end)\n"+
"end\n" +
"return t[2]\n");
runFragment(LuaValue.valueOf("222 222"),
"local t = {}\n" + "local template = [[123 456]]\n" + "for i = 1,2 do\n"
+ " t[i] = template:gsub('%d', function(s)\n" + " return i\n" + " end)\n" + "end\n"
+ "return t[2]\n");
}
public void testReturnUpvalue() {
runFragment( LuaValue.varargsOf(new LuaValue[] { LuaValue.ONE, LuaValue.valueOf(5), }),
"local a = 1\n"+
"local b\n"+
"function c()\n"+
" b=5\n" +
" return a\n"+
"end\n"+
"return c(),b\n" );
runFragment(LuaValue.varargsOf(new LuaValue[] { LuaValue.ONE, LuaValue.valueOf(5), }), "local a = 1\n"
+ "local b\n" + "function c()\n" + " b=5\n" + " return a\n" + "end\n" + "return c(),b\n");
}
public void testUninitializedAroundBranch() {
runFragment( LuaValue.valueOf(333),
"local state\n"+
"if _G then\n"+
" state = 333\n"+
"end\n"+
"return state\n" );
runFragment(LuaValue.valueOf(333),
"local state\n" + "if _G then\n" + " state = 333\n" + "end\n" + "return state\n");
}
public void testLoadedNilUpvalue() {
runFragment( LuaValue.NIL,
"local a = print()\n"+
"local b = c and { d = e }\n"+
"local f\n"+
"local function g()\n"+
" return f\n"+
"end\n" +
"return g()\n" );
runFragment(LuaValue.NIL, "local a = print()\n" + "local b = c and { d = e }\n" + "local f\n"
+ "local function g()\n" + " return f\n" + "end\n" + "return g()\n");
}
public void testUpvalueInFirstSlot() {
runFragment( LuaValue.valueOf("foo"),
"local p = {'foo'}\n"+
"bar = function()\n"+
" return p \n"+
"end\n"+
"for i,key in ipairs(p) do\n"+
" print()\n"+
"end\n" +
"return bar()[1]");
runFragment(LuaValue.valueOf("foo"), "local p = {'foo'}\n" + "bar = function()\n" + " return p \n"
+ "end\n" + "for i,key in ipairs(p) do\n" + " print()\n" + "end\n" + "return bar()[1]");
}
public void testReadOnlyAndReadWriteUpvalues() {
runFragment( LuaValue.varargsOf( new LuaValue[] { LuaValue.valueOf(333), LuaValue.valueOf(222) } ),
"local a = 111\n" +
"local b = 222\n" +
"local c = function()\n"+
" a = a + b\n" +
" return a,b\n"+
"end\n" +
"return c()\n" );
runFragment(LuaValue.varargsOf(new LuaValue[] { LuaValue.valueOf(333), LuaValue.valueOf(222) }),
"local a = 111\n" + "local b = 222\n" + "local c = function()\n" + " a = a + b\n"
+ " return a,b\n" + "end\n" + "return c()\n");
}
public void testNestedUpvalues() {
runFragment( LuaValue.varargsOf( new LuaValue[] { LuaValue.valueOf(5), LuaValue.valueOf(8), LuaValue.valueOf(9) } ),
"local x = 3\n"+
"local y = 5\n"+
"local function f()\n"+
" return y\n"+
"end\n"+
"local function g(x1, y1)\n"+
" x = x1\n"+
" y = y1\n" +
" return x,y\n"+
"end\n"+
"return f(), g(8,9)\n"+
"\n" );
runFragment(
LuaValue.varargsOf(new LuaValue[] { LuaValue.valueOf(5), LuaValue.valueOf(8), LuaValue.valueOf(9) }),
"local x = 3\n" + "local y = 5\n" + "local function f()\n" + " return y\n" + "end\n"
+ "local function g(x1, y1)\n" + " x = x1\n" + " y = y1\n" + " return x,y\n" + "end\n"
+ "return f(), g(8,9)\n" + "\n");
}
public void testLoadBool() {
runFragment( LuaValue.NONE,
"print( type(foo)=='string' )\n"+
"local a,b\n"+
"if print() then\n"+
" b = function()\n"+
" return a\n"+
" end\n"+
"end\n" );
runFragment(LuaValue.NONE, "print( type(foo)=='string' )\n" + "local a,b\n" + "if print() then\n"
+ " b = function()\n" + " return a\n" + " end\n" + "end\n");
}
public void testBasicForLoop() {
runFragment( LuaValue.valueOf(2),
"local data\n"+
"for i = 1, 2 do\n"+
" data = i\n"+
"end\n"+
"local bar = function()\n"+
" return data\n"+
"end\n" +
"return bar()\n" );
runFragment(LuaValue.valueOf(2), "local data\n" + "for i = 1, 2 do\n" + " data = i\n" + "end\n"
+ "local bar = function()\n" + " return data\n" + "end\n" + "return bar()\n");
}
public void testGenericForMultipleValues() {
runFragment( LuaValue.varargsOf(LuaValue.valueOf(3),LuaValue.valueOf(2),LuaValue.valueOf(1)),
"local iter = function() return 1,2,3,4 end\n" +
"local foo = function() return iter,5 end\n" +
"for a,b,c in foo() do\n" +
" return c,b,a\n" +
"end\n" );
runFragment(LuaValue.varargsOf(LuaValue.valueOf(3), LuaValue.valueOf(2), LuaValue.valueOf(1)),
"local iter = function() return 1,2,3,4 end\n" + "local foo = function() return iter,5 end\n"
+ "for a,b,c in foo() do\n" + " return c,b,a\n" + "end\n");
}
public void testPhiUpvalue() {
runFragment( LuaValue.valueOf(6),
"local a = foo or 0\n"+
"local function b(c)\n"+
" if c > a then a = c end\n" +
" return a\n"+
"end\n" +
"b(6)\n" +
"return a\n" );
runFragment(LuaValue.valueOf(6), "local a = foo or 0\n" + "local function b(c)\n"
+ " if c > a then a = c end\n" + " return a\n" + "end\n" + "b(6)\n" + "return a\n");
}
public void testAssignReferUpvalues() {
runFragment( LuaValue.valueOf(123),
"local entity = 234\n" +
"local function c()\n" +
" return entity\n" +
"end\n" +
"entity = (a == b) and 123\n" +
"if entity then\n" +
" return entity\n" +
"end\n" );
runFragment(LuaValue.valueOf(123), "local entity = 234\n" + "local function c()\n" + " return entity\n"
+ "end\n" + "entity = (a == b) and 123\n" + "if entity then\n" + " return entity\n" + "end\n");
}
public void testSimpleRepeatUntil() {
runFragment( LuaValue.valueOf(5),
"local a\n"+
"local w\n"+
"repeat\n"+
" a = w\n"+
"until not a\n" +
"return 5\n" );
runFragment(LuaValue.valueOf(5),
"local a\n" + "local w\n" + "repeat\n" + " a = w\n" + "until not a\n" + "return 5\n");
}
public void testLoopVarUpvalues() {
runFragment( LuaValue.valueOf("b"),
"local env = {}\n" +
"for a,b in pairs(_G) do\n" +
" c = function()\n" +
" return b\n" +
" end\n" +
"end\n" +
"local e = env\n" +
"local f = {a='b'}\n" +
"for k,v in pairs(f) do\n" +
" return env[k] or v\n" +
"end\n");
runFragment(LuaValue.valueOf("b"),
"local env = {}\n" + "for a,b in pairs(_G) do\n" + " c = function()\n" + " return b\n"
+ " end\n" + "end\n" + "local e = env\n" + "local f = {a='b'}\n" + "for k,v in pairs(f) do\n"
+ " return env[k] or v\n" + "end\n");
}
public void testPhiVarUpvalue() {
runFragment( LuaValue.valueOf(2),
"local a = 1\n"+
"local function b()\n"+
" a = a + 1\n"+
" return function() end\n"+
"end\n"+
"for i in b() do\n"+
" a = 3\n"+
"end\n" +
"return a\n");
runFragment(LuaValue.valueOf(2), "local a = 1\n" + "local function b()\n" + " a = a + 1\n"
+ " return function() end\n" + "end\n" + "for i in b() do\n" + " a = 3\n" + "end\n" + "return a\n");
}
public void testUpvaluesInElseClauses() {
runFragment( LuaValue.valueOf(111),
"if a then\n" +
" foo(bar)\n" +
"elseif _G then\n" +
" local x = 111\n" +
" if d then\n" +
" foo(bar)\n" +
" else\n" +
" local y = function()\n" +
" return x\n" +
" end\n" +
" return y()\n" +
" end\n" +
"end\n");
runFragment(LuaValue.valueOf(111),
"if a then\n" + " foo(bar)\n" + "elseif _G then\n" + " local x = 111\n" + " if d then\n"
+ " foo(bar)\n" + " else\n" + " local y = function()\n" + " return x\n"
+ " end\n" + " return y()\n" + " end\n" + "end\n");
}
public void testUpvalueInDoBlock() {
runFragment( LuaValue.NONE, "do\n"+
" local x = 10\n"+
" function g()\n"+
" return x\n"+
" end\n"+
"end\n"+
"g()\n");
runFragment(LuaValue.NONE,
"do\n" + " local x = 10\n" + " function g()\n" + " return x\n" + " end\n" + "end\n" + "g()\n");
}
public void testNullError() {
runFragment( LuaValue.varargsOf(LuaValue.FALSE, LuaValue.NIL),
"return pcall(error)\n");
runFragment(LuaValue.varargsOf(LuaValue.FALSE, LuaValue.NIL), "return pcall(error)\n");
}
public void testFindWithOffset() {
runFragment(LuaValue.varargsOf(LuaValue.valueOf(8), LuaValue.valueOf(5)),
"string = \"abcdef:ghi\"\n" +
"substring = string:sub(3)\n" +
"idx = substring:find(\":\")\n" +
"return #substring, idx\n");
runFragment(LuaValue.varargsOf(LuaValue.valueOf(8), LuaValue.valueOf(5)), "string = \"abcdef:ghi\"\n"
+ "substring = string:sub(3)\n" + "idx = substring:find(\":\")\n" + "return #substring, idx\n");
}
public void testErrorArgIsString() {
runFragment(LuaValue.varargsOf(LuaValue.valueOf("string"), LuaValue.valueOf("c")),
"a,b = pcall(error, 'c'); return type(b), b\n");
"a,b = pcall(error, 'c'); return type(b), b\n");
}
public void testErrorArgIsNil() {
runFragment(LuaValue.varargsOf(LuaValue.valueOf("nil"), LuaValue.NIL),
"a,b = pcall(error); return type(b), b\n");
"a,b = pcall(error); return type(b), b\n");
}
public void testErrorArgIsTable() {
runFragment(LuaValue.varargsOf(LuaValue.valueOf("table"), LuaValue.valueOf("d")),
"a,b = pcall(error, {c='d'}); return type(b), b.c\n");
"a,b = pcall(error, {c='d'}); return type(b), b.c\n");
}
public void testErrorArgIsNumber() {
runFragment(LuaValue.varargsOf(LuaValue.valueOf("string"), LuaValue.valueOf("1")),
"a,b = pcall(error, 1); return type(b), b\n");
"a,b = pcall(error, 1); return type(b), b\n");
}
public void testErrorArgIsBool() {
runFragment(LuaValue.varargsOf(LuaValue.valueOf("boolean"), LuaValue.TRUE),
"a,b = pcall(error, true); return type(b), b\n");
"a,b = pcall(error, true); return type(b), b\n");
}
public void testBalancedMatchOnEmptyString() {
runFragment(LuaValue.NIL, "return (\"\"):match(\"%b''\")\n");
}
public void testReturnValueForTableRemove() {
runFragment(LuaValue.NONE, "return table.remove({ })");
}
public void testTypeOfTableRemoveReturnValue() {
runFragment(LuaValue.valueOf("nil"), "local k = table.remove({ }) return type(k)");
}
public void testVarargBugReport() {
runFragment(LuaValue.varargsOf(new LuaValue[] {
LuaValue.valueOf(1), LuaValue.valueOf(2), LuaValue.valueOf(3) }),
"local i = function(...) return ... end\n"
+ "local v1, v2, v3 = i(1, 2, 3)\n"
+ "return v1, v2, v3");
runFragment(
LuaValue.varargsOf(new LuaValue[] { LuaValue.valueOf(1), LuaValue.valueOf(2), LuaValue.valueOf(3) }),
"local i = function(...) return ... end\n" + "local v1, v2, v3 = i(1, 2, 3)\n" + "return v1, v2, v3");
}
}
}

View File

@@ -61,8 +61,7 @@ public class LoadOrderTest extends TestCase {
}
public void testClassLoadsStringFirst() throws Exception {
Launcher launcher = LuajClassLoader
.NewLauncher(TestLauncherLoadStringFirst.class);
Launcher launcher = LuajClassLoader.NewLauncher(TestLauncherLoadStringFirst.class);
Object[] results = launcher.launch("foo", null);
assertNotNull(results);
}

View File

@@ -32,103 +32,106 @@ import org.luaj.vm2.compiler.LuaC;
import org.luaj.vm2.lib.ZeroArgFunction;
public class LuaOperationsTest extends TestCase {
private final int sampleint = 77;
private final long samplelong = 123400000000L;
private final double sampledouble = 55.25;
private final int sampleint = 77;
private final long samplelong = 123400000000L;
private final double sampledouble = 55.25;
private final String samplestringstring = "abcdef";
private final String samplestringint = String.valueOf(sampleint);
private final String samplestringlong = String.valueOf(samplelong);
private final String samplestringint = String.valueOf(sampleint);
private final String samplestringlong = String.valueOf(samplelong);
private final String samplestringdouble = String.valueOf(sampledouble);
private final Object sampleobject = new Object();
private final MyData sampledata = new MyData();
private final LuaValue somenil = LuaValue.NIL;
private final LuaValue sometrue = LuaValue.TRUE;
private final LuaValue somefalse = LuaValue.FALSE;
private final LuaValue zero = LuaValue.ZERO;
private final LuaValue intint = LuaValue.valueOf(sampleint);
private final LuaValue longdouble = LuaValue.valueOf(samplelong);
private final LuaValue doubledouble = LuaValue.valueOf(sampledouble);
private final LuaValue stringstring = LuaValue.valueOf(samplestringstring);
private final LuaValue stringint = LuaValue.valueOf(samplestringint);
private final LuaValue stringlong = LuaValue.valueOf(samplestringlong);
private final LuaValue stringdouble = LuaValue.valueOf(samplestringdouble);
private final LuaTable table = LuaValue.listOf( new LuaValue[] { LuaValue.valueOf("aaa"), LuaValue.valueOf("bbb") } );
private final LuaValue somefunc = new ZeroArgFunction() { public LuaValue call() { return NONE;}};
private final LuaThread thread = new LuaThread(new Globals(), somefunc);
private final Prototype proto = new Prototype(1);
private final LuaClosure someclosure = new LuaClosure(proto,table);
private final LuaUserdata userdataobj = LuaValue.userdataOf(sampleobject);
private final LuaUserdata userdatacls = LuaValue.userdataOf(sampledata);
private final Object sampleobject = new Object();
private final MyData sampledata = new MyData();
private final LuaValue somenil = LuaValue.NIL;
private final LuaValue sometrue = LuaValue.TRUE;
private final LuaValue somefalse = LuaValue.FALSE;
private final LuaValue zero = LuaValue.ZERO;
private final LuaValue intint = LuaValue.valueOf(sampleint);
private final LuaValue longdouble = LuaValue.valueOf(samplelong);
private final LuaValue doubledouble = LuaValue.valueOf(sampledouble);
private final LuaValue stringstring = LuaValue.valueOf(samplestringstring);
private final LuaValue stringint = LuaValue.valueOf(samplestringint);
private final LuaValue stringlong = LuaValue.valueOf(samplestringlong);
private final LuaValue stringdouble = LuaValue.valueOf(samplestringdouble);
private final LuaTable table = LuaValue
.listOf(new LuaValue[] { LuaValue.valueOf("aaa"), LuaValue.valueOf("bbb") });
private final LuaValue somefunc = new ZeroArgFunction() {
public LuaValue call() { return NONE; }
};
private final LuaThread thread = new LuaThread(new Globals(), somefunc);
private final Prototype proto = new Prototype(1);
private final LuaClosure someclosure = new LuaClosure(proto, table);
private final LuaUserdata userdataobj = LuaValue.userdataOf(sampleobject);
private final LuaUserdata userdatacls = LuaValue.userdataOf(sampledata);
private void throwsLuaError(String methodName, Object obj) {
try {
LuaValue.class.getMethod(methodName).invoke(obj);
fail("failed to throw LuaError as required");
} catch (InvocationTargetException e) {
if ( ! (e.getTargetException() instanceof LuaError) )
fail("not a LuaError: "+e.getTargetException());
if (!(e.getTargetException() instanceof LuaError))
fail("not a LuaError: " + e.getTargetException());
return; // pass
} catch ( Exception e ) {
fail( "bad exception: "+e );
} catch (Exception e) {
fail("bad exception: " + e);
}
}
private void throwsLuaError(String methodName, Object obj, Object arg) {
try {
LuaValue.class.getMethod(methodName,LuaValue.class).invoke(obj,arg);
fail("failed to throw LuaError as required");
} catch (InvocationTargetException e) {
if ( ! (e.getTargetException() instanceof LuaError) )
fail("not a LuaError: "+e.getTargetException());
return; // pass
} catch ( Exception e ) {
fail( "bad exception: "+e );
}
}
public void testLen() {
throwsLuaError( "len", somenil );
throwsLuaError( "len", sometrue );
throwsLuaError( "len", somefalse );
throwsLuaError( "len", zero );
throwsLuaError( "len", intint );
throwsLuaError( "len", longdouble );
throwsLuaError( "len", doubledouble );
assertEquals( LuaInteger.valueOf(samplestringstring.length()), stringstring.len() );
assertEquals( LuaInteger.valueOf(samplestringint.length()), stringint.len() );
assertEquals( LuaInteger.valueOf(samplestringlong.length()), stringlong.len() );
assertEquals( LuaInteger.valueOf(samplestringdouble.length()), stringdouble.len() );
assertEquals( LuaInteger.valueOf(2), table.len() );
throwsLuaError( "len", somefunc );
throwsLuaError( "len", thread );
throwsLuaError( "len", someclosure );
throwsLuaError( "len", userdataobj );
throwsLuaError( "len", userdatacls );
}
public void testLength() {
throwsLuaError( "length", somenil );
throwsLuaError( "length", sometrue );
throwsLuaError( "length", somefalse );
throwsLuaError( "length", zero );
throwsLuaError( "length", intint );
throwsLuaError( "length", longdouble );
throwsLuaError( "length", doubledouble );
assertEquals( samplestringstring.length(), stringstring.length() );
assertEquals( samplestringint.length(), stringint.length() );
assertEquals( samplestringlong.length(), stringlong.length() );
assertEquals( samplestringdouble.length(), stringdouble.length() );
assertEquals( 2, table.length() );
throwsLuaError( "length", somefunc );
throwsLuaError( "length", thread );
throwsLuaError( "length", someclosure );
throwsLuaError( "length", userdataobj );
throwsLuaError( "length", userdatacls );
}
public Prototype createPrototype( String script, String name ) {
private void throwsLuaError(String methodName, Object obj, Object arg) {
try {
LuaValue.class.getMethod(methodName, LuaValue.class).invoke(obj, arg);
fail("failed to throw LuaError as required");
} catch (InvocationTargetException e) {
if (!(e.getTargetException() instanceof LuaError))
fail("not a LuaError: " + e.getTargetException());
return; // pass
} catch (Exception e) {
fail("bad exception: " + e);
}
}
public void testLen() {
throwsLuaError("len", somenil);
throwsLuaError("len", sometrue);
throwsLuaError("len", somefalse);
throwsLuaError("len", zero);
throwsLuaError("len", intint);
throwsLuaError("len", longdouble);
throwsLuaError("len", doubledouble);
assertEquals(LuaInteger.valueOf(samplestringstring.length()), stringstring.len());
assertEquals(LuaInteger.valueOf(samplestringint.length()), stringint.len());
assertEquals(LuaInteger.valueOf(samplestringlong.length()), stringlong.len());
assertEquals(LuaInteger.valueOf(samplestringdouble.length()), stringdouble.len());
assertEquals(LuaInteger.valueOf(2), table.len());
throwsLuaError("len", somefunc);
throwsLuaError("len", thread);
throwsLuaError("len", someclosure);
throwsLuaError("len", userdataobj);
throwsLuaError("len", userdatacls);
}
public void testLength() {
throwsLuaError("length", somenil);
throwsLuaError("length", sometrue);
throwsLuaError("length", somefalse);
throwsLuaError("length", zero);
throwsLuaError("length", intint);
throwsLuaError("length", longdouble);
throwsLuaError("length", doubledouble);
assertEquals(samplestringstring.length(), stringstring.length());
assertEquals(samplestringint.length(), stringint.length());
assertEquals(samplestringlong.length(), stringlong.length());
assertEquals(samplestringdouble.length(), stringdouble.length());
assertEquals(2, table.length());
throwsLuaError("length", somefunc);
throwsLuaError("length", thread);
throwsLuaError("length", someclosure);
throwsLuaError("length", userdataobj);
throwsLuaError("length", userdatacls);
}
public Prototype createPrototype(String script, String name) {
try {
Globals globals = org.luaj.vm2.lib.jse.JsePlatform.standardGlobals();
Reader reader = new StringReader(script);
@@ -138,7 +141,7 @@ public class LuaOperationsTest extends TestCase {
e.printStackTrace();
fail(e.toString());
return null;
}
}
}
public void testFunctionClosureThreadEnv() {
@@ -147,30 +150,31 @@ public class LuaOperationsTest extends TestCase {
LuaValue aaa = LuaValue.valueOf("aaa");
LuaValue eee = LuaValue.valueOf("eee");
final Globals globals = org.luaj.vm2.lib.jse.JsePlatform.standardGlobals();
LuaTable newenv = LuaValue.tableOf( new LuaValue[] {
LuaValue.valueOf("a"), LuaValue.valueOf("aaa"),
LuaValue.valueOf("b"), LuaValue.valueOf("bbb"), } );
LuaTable mt = LuaValue.tableOf( new LuaValue[] { LuaValue.INDEX, globals } );
LuaTable newenv = LuaValue.tableOf(new LuaValue[] { LuaValue.valueOf("a"), LuaValue.valueOf("aaa"),
LuaValue.valueOf("b"), LuaValue.valueOf("bbb"), });
LuaTable mt = LuaValue.tableOf(new LuaValue[] { LuaValue.INDEX, globals });
newenv.setmetatable(mt);
globals.set("a", aaa);
newenv.set("a", eee);
// function tests
{
LuaFunction f = new ZeroArgFunction() { public LuaValue call() { return globals.get("a");}};
assertEquals( aaa, f.call() );
LuaFunction f = new ZeroArgFunction() {
public LuaValue call() { return globals.get("a"); }
};
assertEquals(aaa, f.call());
}
// closure tests
{
Prototype p = createPrototype( "return a\n", "closuretester" );
Prototype p = createPrototype("return a\n", "closuretester");
LuaClosure c = new LuaClosure(p, globals);
// Test that a clusure with a custom enviroment uses that environment.
assertEquals( aaa, c.call() );
assertEquals(aaa, c.call());
c = new LuaClosure(p, newenv);
assertEquals( newenv, c.upValues[0].getValue() );
assertEquals( eee, c.call() );
assertEquals(newenv, c.upValues[0].getValue());
assertEquals(eee, c.call());
}
}
}

View File

@@ -9,224 +9,224 @@ public class MathLibTest extends TestCase {
private LuaValue j2se;
private LuaValue j2me;
private boolean supportedOnJ2me;
private boolean supportedOnJ2me;
public MathLibTest() {
j2se = JsePlatform.standardGlobals().get("math");
j2me = JmePlatform.standardGlobals().get("math");
}
protected void setUp() throws Exception {
supportedOnJ2me = true;
}
public void testMathDPow() {
assertEquals( 1, j2mepow(2, 0), 0 );
assertEquals( 2, j2mepow(2, 1), 0 );
assertEquals( 8, j2mepow(2, 3), 0 );
assertEquals( -8, j2mepow(-2, 3), 0 );
assertEquals( 1/8., j2mepow(2, -3), 0 );
assertEquals( -1/8., j2mepow(-2, -3), 0 );
assertEquals( 16, j2mepow(256, .5), 0 );
assertEquals( 4, j2mepow(256, .25), 0 );
assertEquals( 64, j2mepow(256, .75), 0 );
assertEquals( 1./16, j2mepow(256, - .5), 0 );
assertEquals( 1./ 4, j2mepow(256, -.25), 0 );
assertEquals( 1./64, j2mepow(256, -.75), 0 );
assertEquals( Double.NaN, j2mepow(-256, .5), 0 );
assertEquals( 1, j2mepow(.5, 0), 0 );
assertEquals( .5, j2mepow(.5, 1), 0 );
assertEquals(.125, j2mepow(.5, 3), 0 );
assertEquals( 2, j2mepow(.5, -1), 0 );
assertEquals( 8, j2mepow(.5, -3), 0 );
assertEquals(1, j2mepow(0.0625, 0), 0 );
assertEquals(0.00048828125, j2mepow(0.0625, 2.75), 0 );
assertEquals(1, j2mepow(2, 0), 0);
assertEquals(2, j2mepow(2, 1), 0);
assertEquals(8, j2mepow(2, 3), 0);
assertEquals(-8, j2mepow(-2, 3), 0);
assertEquals(1/8., j2mepow(2, -3), 0);
assertEquals(-1/8., j2mepow(-2, -3), 0);
assertEquals(16, j2mepow(256, .5), 0);
assertEquals(4, j2mepow(256, .25), 0);
assertEquals(64, j2mepow(256, .75), 0);
assertEquals(1./16, j2mepow(256, -.5), 0);
assertEquals(1./4, j2mepow(256, -.25), 0);
assertEquals(1./64, j2mepow(256, -.75), 0);
assertEquals(Double.NaN, j2mepow(-256, .5), 0);
assertEquals(1, j2mepow(.5, 0), 0);
assertEquals(.5, j2mepow(.5, 1), 0);
assertEquals(.125, j2mepow(.5, 3), 0);
assertEquals(2, j2mepow(.5, -1), 0);
assertEquals(8, j2mepow(.5, -3), 0);
assertEquals(1, j2mepow(0.0625, 0), 0);
assertEquals(0.00048828125, j2mepow(0.0625, 2.75), 0);
}
private double j2mepow(double x, double y) {
return j2me.get("pow").call(LuaValue.valueOf(x),LuaValue.valueOf(y)).todouble();
return j2me.get("pow").call(LuaValue.valueOf(x), LuaValue.valueOf(y)).todouble();
}
public void testAbs() {
tryMathOp( "abs", 23.45 );
tryMathOp( "abs", -23.45 );
tryMathOp("abs", 23.45);
tryMathOp("abs", -23.45);
}
public void testCos() {
tryTrigOps( "cos" );
tryTrigOps("cos");
}
public void testCosh() {
supportedOnJ2me = false;
tryTrigOps( "cosh" );
tryTrigOps("cosh");
}
public void testDeg() {
tryTrigOps( "deg" );
tryTrigOps("deg");
}
public void testExp() {
//supportedOnJ2me = false;
tryMathOp( "exp", 0 );
tryMathOp( "exp", 0.1 );
tryMathOp( "exp", .9 );
tryMathOp( "exp", 1. );
tryMathOp( "exp", 9 );
tryMathOp( "exp", -.1 );
tryMathOp( "exp", -.9 );
tryMathOp( "exp", -1. );
tryMathOp( "exp", -9 );
tryMathOp("exp", 0);
tryMathOp("exp", 0.1);
tryMathOp("exp", .9);
tryMathOp("exp", 1.);
tryMathOp("exp", 9);
tryMathOp("exp", -.1);
tryMathOp("exp", -.9);
tryMathOp("exp", -1.);
tryMathOp("exp", -9);
}
public void testLog() {
supportedOnJ2me = false;
tryMathOp( "log", 0.1 );
tryMathOp( "log", .9 );
tryMathOp( "log", 1. );
tryMathOp( "log", 9 );
tryMathOp( "log", -.1 );
tryMathOp( "log", -.9 );
tryMathOp( "log", -1. );
tryMathOp( "log", -9 );
tryMathOp("log", 0.1);
tryMathOp("log", .9);
tryMathOp("log", 1.);
tryMathOp("log", 9);
tryMathOp("log", -.1);
tryMathOp("log", -.9);
tryMathOp("log", -1.);
tryMathOp("log", -9);
}
public void testRad() {
tryMathOp( "rad", 0 );
tryMathOp( "rad", 0.1 );
tryMathOp( "rad", .9 );
tryMathOp( "rad", 1. );
tryMathOp( "rad", 9 );
tryMathOp( "rad", 10 );
tryMathOp( "rad", 100 );
tryMathOp( "rad", -.1 );
tryMathOp( "rad", -.9 );
tryMathOp( "rad", -1. );
tryMathOp( "rad", -9 );
tryMathOp( "rad", -10 );
tryMathOp( "rad", -100 );
tryMathOp("rad", 0);
tryMathOp("rad", 0.1);
tryMathOp("rad", .9);
tryMathOp("rad", 1.);
tryMathOp("rad", 9);
tryMathOp("rad", 10);
tryMathOp("rad", 100);
tryMathOp("rad", -.1);
tryMathOp("rad", -.9);
tryMathOp("rad", -1.);
tryMathOp("rad", -9);
tryMathOp("rad", -10);
tryMathOp("rad", -100);
}
public void testSin() {
tryTrigOps( "sin" );
tryTrigOps("sin");
}
public void testSinh() {
supportedOnJ2me = false;
tryTrigOps( "sinh" );
tryTrigOps("sinh");
}
public void testSqrt() {
tryMathOp( "sqrt", 0 );
tryMathOp( "sqrt", 0.1 );
tryMathOp( "sqrt", .9 );
tryMathOp( "sqrt", 1. );
tryMathOp( "sqrt", 9 );
tryMathOp( "sqrt", 10 );
tryMathOp( "sqrt", 100 );
tryMathOp("sqrt", 0);
tryMathOp("sqrt", 0.1);
tryMathOp("sqrt", .9);
tryMathOp("sqrt", 1.);
tryMathOp("sqrt", 9);
tryMathOp("sqrt", 10);
tryMathOp("sqrt", 100);
}
public void testTan() {
tryTrigOps( "tan" );
tryTrigOps("tan");
}
public void testTanh() {
supportedOnJ2me = false;
tryTrigOps( "tanh" );
tryTrigOps("tanh");
}
public void testAtan2() {
supportedOnJ2me = false;
tryDoubleOps( "atan2", false );
tryDoubleOps("atan2", false);
}
public void testFmod() {
tryDoubleOps( "fmod", false );
tryDoubleOps("fmod", false);
}
public void testPow() {
tryDoubleOps( "pow", true );
tryDoubleOps("pow", true);
}
private void tryDoubleOps( String op, boolean positiveOnly ) {
private void tryDoubleOps(String op, boolean positiveOnly) {
// y>0, x>0
tryMathOp( op, 0.1, 4.0 );
tryMathOp( op, .9, 4.0 );
tryMathOp( op, 1., 4.0 );
tryMathOp( op, 9, 4.0 );
tryMathOp( op, 10, 4.0 );
tryMathOp( op, 100, 4.0 );
tryMathOp(op, 0.1, 4.0);
tryMathOp(op, .9, 4.0);
tryMathOp(op, 1., 4.0);
tryMathOp(op, 9, 4.0);
tryMathOp(op, 10, 4.0);
tryMathOp(op, 100, 4.0);
// y>0, x<0
tryMathOp( op, 0.1, -4.0 );
tryMathOp( op, .9, -4.0 );
tryMathOp( op, 1., -4.0 );
tryMathOp( op, 9, -4.0 );
tryMathOp( op, 10, -4.0 );
tryMathOp( op, 100, -4.0 );
if ( ! positiveOnly ) {
tryMathOp(op, 0.1, -4.0);
tryMathOp(op, .9, -4.0);
tryMathOp(op, 1., -4.0);
tryMathOp(op, 9, -4.0);
tryMathOp(op, 10, -4.0);
tryMathOp(op, 100, -4.0);
if (!positiveOnly) {
// y<0, x>0
tryMathOp( op, -0.1, 4.0 );
tryMathOp( op, -.9, 4.0 );
tryMathOp( op, -1., 4.0 );
tryMathOp( op, -9, 4.0 );
tryMathOp( op, -10, 4.0 );
tryMathOp( op, -100, 4.0 );
tryMathOp(op, -0.1, 4.0);
tryMathOp(op, -.9, 4.0);
tryMathOp(op, -1., 4.0);
tryMathOp(op, -9, 4.0);
tryMathOp(op, -10, 4.0);
tryMathOp(op, -100, 4.0);
// y<0, x<0
tryMathOp( op, -0.1, -4.0 );
tryMathOp( op, -.9, -4.0 );
tryMathOp( op, -1., -4.0 );
tryMathOp( op, -9, -4.0 );
tryMathOp( op, -10, -4.0 );
tryMathOp( op, -100, -4.0 );
tryMathOp(op, -0.1, -4.0);
tryMathOp(op, -.9, -4.0);
tryMathOp(op, -1., -4.0);
tryMathOp(op, -9, -4.0);
tryMathOp(op, -10, -4.0);
tryMathOp(op, -100, -4.0);
}
// degenerate cases
tryMathOp( op, 0, 1 );
tryMathOp( op, 1, 0 );
tryMathOp( op, -1, 0 );
tryMathOp( op, 0, -1 );
tryMathOp( op, 0, 0 );
tryMathOp(op, 0, 1);
tryMathOp(op, 1, 0);
tryMathOp(op, -1, 0);
tryMathOp(op, 0, -1);
tryMathOp(op, 0, 0);
}
private void tryTrigOps(String op) {
tryMathOp( op, 0 );
tryMathOp( op, Math.PI/8 );
tryMathOp( op, Math.PI*7/8 );
tryMathOp( op, Math.PI*8/8 );
tryMathOp( op, Math.PI*9/8 );
tryMathOp( op, -Math.PI/8 );
tryMathOp( op, -Math.PI*7/8 );
tryMathOp( op, -Math.PI*8/8 );
tryMathOp( op, -Math.PI*9/8 );
tryMathOp(op, 0);
tryMathOp(op, Math.PI/8);
tryMathOp(op, Math.PI*7/8);
tryMathOp(op, Math.PI*8/8);
tryMathOp(op, Math.PI*9/8);
tryMathOp(op, -Math.PI/8);
tryMathOp(op, -Math.PI*7/8);
tryMathOp(op, -Math.PI*8/8);
tryMathOp(op, -Math.PI*9/8);
}
private void tryMathOp(String op, double x) {
private void tryMathOp(String op, double x) {
try {
double expected = j2se.get(op).call( LuaValue.valueOf(x)).todouble();
double actual = j2me.get(op).call( LuaValue.valueOf(x)).todouble();
if ( supportedOnJ2me )
assertEquals( expected, actual, 1.e-4 );
double expected = j2se.get(op).call(LuaValue.valueOf(x)).todouble();
double actual = j2me.get(op).call(LuaValue.valueOf(x)).todouble();
if (supportedOnJ2me)
assertEquals(expected, actual, 1.e-4);
else
fail("j2me should throw exception for math."+op+" but returned "+actual);
} catch ( LuaError lee ) {
if ( supportedOnJ2me )
fail("j2me should throw exception for math." + op + " but returned " + actual);
} catch (LuaError lee) {
if (supportedOnJ2me)
throw lee;
}
}
private void tryMathOp(String op, double a, double b) {
try {
double expected = j2se.get(op).call( LuaValue.valueOf(a), LuaValue.valueOf(b)).todouble();
double actual = j2me.get(op).call( LuaValue.valueOf(a), LuaValue.valueOf(b)).todouble();
if ( supportedOnJ2me )
assertEquals( expected, actual, 1.e-5 );
double expected = j2se.get(op).call(LuaValue.valueOf(a), LuaValue.valueOf(b)).todouble();
double actual = j2me.get(op).call(LuaValue.valueOf(a), LuaValue.valueOf(b)).todouble();
if (supportedOnJ2me)
assertEquals(expected, actual, 1.e-5);
else
fail("j2me should throw exception for math."+op+" but returned "+actual);
} catch ( LuaError lee ) {
if ( supportedOnJ2me )
fail("j2me should throw exception for math." + op + " but returned " + actual);
} catch (LuaError lee) {
if (supportedOnJ2me)
throw lee;
}
}
}
}

View File

@@ -33,16 +33,18 @@ public class MetatableTest extends TestCase {
private final String samplestring = "abcdef";
private final Object sampleobject = new Object();
private final MyData sampledata = new MyData();
private final LuaValue string = LuaValue.valueOf(samplestring);
private final LuaTable table = LuaValue.tableOf();
private final LuaFunction function = new ZeroArgFunction() { public LuaValue call() { return NONE;}};
private final LuaThread thread = new LuaThread(new Globals(), function);
private final LuaClosure closure = new LuaClosure(new Prototype(), new LuaTable());
private final LuaUserdata userdata = LuaValue.userdataOf(sampleobject);
private final LuaUserdata userdatamt = LuaValue.userdataOf(sampledata,table);
private final MyData sampledata = new MyData();
private final LuaValue string = LuaValue.valueOf(samplestring);
private final LuaTable table = LuaValue.tableOf();
private final LuaFunction function = new ZeroArgFunction() {
public LuaValue call() { return NONE; }
};
private final LuaThread thread = new LuaThread(new Globals(), function);
private final LuaClosure closure = new LuaClosure(new Prototype(), new LuaTable());
private final LuaUserdata userdata = LuaValue.userdataOf(sampleobject);
private final LuaUserdata userdatamt = LuaValue.userdataOf(sampledata, table);
protected void setUp() throws Exception {
// needed for metatable ops to work on strings
new StringLib();
@@ -59,223 +61,218 @@ public class MetatableTest extends TestCase {
}
public void testGetMetatable() {
assertEquals( null, LuaValue.NIL.getmetatable() );
assertEquals( null, LuaValue.TRUE.getmetatable() );
assertEquals( null, LuaValue.ONE.getmetatable() );
assertEquals(null, LuaValue.NIL.getmetatable());
assertEquals(null, LuaValue.TRUE.getmetatable());
assertEquals(null, LuaValue.ONE.getmetatable());
// assertEquals( null, string.getmetatable() );
assertEquals( null, table.getmetatable() );
assertEquals( null, function.getmetatable() );
assertEquals( null, thread.getmetatable() );
assertEquals( null, closure.getmetatable() );
assertEquals( null, userdata.getmetatable() );
assertEquals( table, userdatamt.getmetatable() );
assertEquals(null, table.getmetatable());
assertEquals(null, function.getmetatable());
assertEquals(null, thread.getmetatable());
assertEquals(null, closure.getmetatable());
assertEquals(null, userdata.getmetatable());
assertEquals(table, userdatamt.getmetatable());
}
public void testSetMetatable() {
LuaValue mt = LuaValue.tableOf();
assertEquals( null, table.getmetatable() );
assertEquals( null, userdata.getmetatable() );
assertEquals( table, userdatamt.getmetatable() );
assertEquals( table, table.setmetatable(mt) );
assertEquals( userdata, userdata.setmetatable(mt) );
assertEquals( userdatamt, userdatamt.setmetatable(mt) );
assertEquals( mt, table.getmetatable() );
assertEquals( mt, userdata.getmetatable() );
assertEquals( mt, userdatamt.getmetatable() );
assertEquals(null, table.getmetatable());
assertEquals(null, userdata.getmetatable());
assertEquals(table, userdatamt.getmetatable());
assertEquals(table, table.setmetatable(mt));
assertEquals(userdata, userdata.setmetatable(mt));
assertEquals(userdatamt, userdatamt.setmetatable(mt));
assertEquals(mt, table.getmetatable());
assertEquals(mt, userdata.getmetatable());
assertEquals(mt, userdatamt.getmetatable());
// these all get metatable behind-the-scenes
assertEquals( null, LuaValue.NIL.getmetatable() );
assertEquals( null, LuaValue.TRUE.getmetatable() );
assertEquals( null, LuaValue.ONE.getmetatable() );
assertEquals(null, LuaValue.NIL.getmetatable());
assertEquals(null, LuaValue.TRUE.getmetatable());
assertEquals(null, LuaValue.ONE.getmetatable());
// assertEquals( null, string.getmetatable() );
assertEquals( null, function.getmetatable() );
assertEquals( null, thread.getmetatable() );
assertEquals( null, closure.getmetatable() );
assertEquals(null, function.getmetatable());
assertEquals(null, thread.getmetatable());
assertEquals(null, closure.getmetatable());
LuaNil.s_metatable = mt;
assertEquals( mt, LuaValue.NIL.getmetatable() );
assertEquals( null, LuaValue.TRUE.getmetatable() );
assertEquals( null, LuaValue.ONE.getmetatable() );
assertEquals(mt, LuaValue.NIL.getmetatable());
assertEquals(null, LuaValue.TRUE.getmetatable());
assertEquals(null, LuaValue.ONE.getmetatable());
// assertEquals( null, string.getmetatable() );
assertEquals( null, function.getmetatable() );
assertEquals( null, thread.getmetatable() );
assertEquals( null, closure.getmetatable() );
assertEquals(null, function.getmetatable());
assertEquals(null, thread.getmetatable());
assertEquals(null, closure.getmetatable());
LuaBoolean.s_metatable = mt;
assertEquals( mt, LuaValue.TRUE.getmetatable() );
assertEquals( null, LuaValue.ONE.getmetatable() );
assertEquals(mt, LuaValue.TRUE.getmetatable());
assertEquals(null, LuaValue.ONE.getmetatable());
// assertEquals( null, string.getmetatable() );
assertEquals( null, function.getmetatable() );
assertEquals( null, thread.getmetatable() );
assertEquals( null, closure.getmetatable() );
assertEquals(null, function.getmetatable());
assertEquals(null, thread.getmetatable());
assertEquals(null, closure.getmetatable());
LuaNumber.s_metatable = mt;
assertEquals( mt, LuaValue.ONE.getmetatable() );
assertEquals( mt, LuaValue.valueOf(1.25).getmetatable() );
assertEquals(mt, LuaValue.ONE.getmetatable());
assertEquals(mt, LuaValue.valueOf(1.25).getmetatable());
// assertEquals( null, string.getmetatable() );
assertEquals( null, function.getmetatable() );
assertEquals( null, thread.getmetatable() );
assertEquals( null, closure.getmetatable() );
assertEquals(null, function.getmetatable());
assertEquals(null, thread.getmetatable());
assertEquals(null, closure.getmetatable());
// LuaString.s_metatable = mt;
// assertEquals( mt, string.getmetatable() );
assertEquals( null, function.getmetatable() );
assertEquals( null, thread.getmetatable() );
assertEquals( null, closure.getmetatable() );
assertEquals(null, function.getmetatable());
assertEquals(null, thread.getmetatable());
assertEquals(null, closure.getmetatable());
LuaFunction.s_metatable = mt;
assertEquals( mt, function.getmetatable() );
assertEquals( null, thread.getmetatable() );
assertEquals(mt, function.getmetatable());
assertEquals(null, thread.getmetatable());
LuaThread.s_metatable = mt;
assertEquals( mt, thread.getmetatable() );
assertEquals(mt, thread.getmetatable());
}
public void testMetatableIndex() {
assertEquals( table, table.setmetatable(null) );
assertEquals( userdata, userdata.setmetatable(null) );
assertEquals( userdatamt, userdatamt.setmetatable(null) );
assertEquals( LuaValue.NIL, table.get(1) );
assertEquals( LuaValue.NIL, userdata.get(1) );
assertEquals( LuaValue.NIL, userdatamt.get(1) );
assertEquals(table, table.setmetatable(null));
assertEquals(userdata, userdata.setmetatable(null));
assertEquals(userdatamt, userdatamt.setmetatable(null));
assertEquals(LuaValue.NIL, table.get(1));
assertEquals(LuaValue.NIL, userdata.get(1));
assertEquals(LuaValue.NIL, userdatamt.get(1));
// empty metatable
LuaValue mt = LuaValue.tableOf();
assertEquals( table, table.setmetatable(mt) );
assertEquals( userdata, userdata.setmetatable(mt) );
assertEquals(table, table.setmetatable(mt));
assertEquals(userdata, userdata.setmetatable(mt));
LuaBoolean.s_metatable = mt;
LuaFunction.s_metatable = mt;
LuaNil.s_metatable = mt;
LuaNumber.s_metatable = mt;
// LuaString.s_metatable = mt;
LuaThread.s_metatable = mt;
assertEquals( mt, table.getmetatable() );
assertEquals( mt, userdata.getmetatable() );
assertEquals( mt, LuaValue.NIL.getmetatable() );
assertEquals( mt, LuaValue.TRUE.getmetatable() );
assertEquals( mt, LuaValue.ONE.getmetatable() );
assertEquals(mt, table.getmetatable());
assertEquals(mt, userdata.getmetatable());
assertEquals(mt, LuaValue.NIL.getmetatable());
assertEquals(mt, LuaValue.TRUE.getmetatable());
assertEquals(mt, LuaValue.ONE.getmetatable());
// assertEquals( StringLib.instance, string.getmetatable() );
assertEquals( mt, function.getmetatable() );
assertEquals( mt, thread.getmetatable() );
assertEquals(mt, function.getmetatable());
assertEquals(mt, thread.getmetatable());
// plain metatable
LuaValue abc = LuaValue.valueOf("abc");
mt.set( LuaValue.INDEX, LuaValue.listOf(new LuaValue[] { abc } ) );
assertEquals( abc, table.get(1) );
assertEquals( abc, userdata.get(1) );
assertEquals( abc, LuaValue.NIL.get(1) );
assertEquals( abc, LuaValue.TRUE.get(1) );
assertEquals( abc, LuaValue.ONE.get(1) );
mt.set(LuaValue.INDEX, LuaValue.listOf(new LuaValue[] { abc }));
assertEquals(abc, table.get(1));
assertEquals(abc, userdata.get(1));
assertEquals(abc, LuaValue.NIL.get(1));
assertEquals(abc, LuaValue.TRUE.get(1));
assertEquals(abc, LuaValue.ONE.get(1));
// assertEquals( abc, string.get(1) );
assertEquals( abc, function.get(1) );
assertEquals( abc, thread.get(1) );
assertEquals(abc, function.get(1));
assertEquals(abc, thread.get(1));
// plain metatable
mt.set( LuaValue.INDEX, new TwoArgFunction() {
mt.set(LuaValue.INDEX, new TwoArgFunction() {
public LuaValue call(LuaValue arg1, LuaValue arg2) {
return LuaValue.valueOf( arg1.typename()+"["+arg2.tojstring()+"]=xyz" );
return LuaValue.valueOf(arg1.typename() + "[" + arg2.tojstring() + "]=xyz");
}
});
assertEquals( "table[1]=xyz", table.get(1).tojstring() );
assertEquals( "userdata[1]=xyz", userdata.get(1).tojstring() );
assertEquals( "nil[1]=xyz", LuaValue.NIL.get(1).tojstring() );
assertEquals( "boolean[1]=xyz", LuaValue.TRUE.get(1).tojstring() );
assertEquals( "number[1]=xyz", LuaValue.ONE.get(1).tojstring() );
// assertEquals( "string[1]=xyz", string.get(1).tojstring() );
assertEquals( "function[1]=xyz", function.get(1).tojstring() );
assertEquals( "thread[1]=xyz", thread.get(1).tojstring() );
assertEquals("table[1]=xyz", table.get(1).tojstring());
assertEquals("userdata[1]=xyz", userdata.get(1).tojstring());
assertEquals("nil[1]=xyz", LuaValue.NIL.get(1).tojstring());
assertEquals("boolean[1]=xyz", LuaValue.TRUE.get(1).tojstring());
assertEquals("number[1]=xyz", LuaValue.ONE.get(1).tojstring());
// assertEquals( "string[1]=xyz", string.get(1).tojstring() );
assertEquals("function[1]=xyz", function.get(1).tojstring());
assertEquals("thread[1]=xyz", thread.get(1).tojstring());
}
public void testMetatableNewIndex() {
// empty metatable
LuaValue mt = LuaValue.tableOf();
assertEquals( table, table.setmetatable(mt) );
assertEquals( userdata, userdata.setmetatable(mt) );
assertEquals(table, table.setmetatable(mt));
assertEquals(userdata, userdata.setmetatable(mt));
LuaBoolean.s_metatable = mt;
LuaFunction.s_metatable = mt;
LuaNil.s_metatable = mt;
LuaNumber.s_metatable = mt;
// LuaString.s_metatable = mt;
LuaThread.s_metatable = mt;
// plain metatable
final LuaValue fallback = LuaValue.tableOf();
LuaValue abc = LuaValue.valueOf("abc");
mt.set( LuaValue.NEWINDEX, fallback );
table.set(2,abc);
userdata.set(3,abc);
LuaValue.NIL.set(4,abc);
LuaValue.TRUE.set(5,abc);
LuaValue.ONE.set(6,abc);
mt.set(LuaValue.NEWINDEX, fallback);
table.set(2, abc);
userdata.set(3, abc);
LuaValue.NIL.set(4, abc);
LuaValue.TRUE.set(5, abc);
LuaValue.ONE.set(6, abc);
// string.set(7,abc);
function.set(8,abc);
thread.set(9,abc);
assertEquals( abc, fallback.get(2) );
assertEquals( abc, fallback.get(3) );
assertEquals( abc, fallback.get(4) );
assertEquals( abc, fallback.get(5) );
assertEquals( abc, fallback.get(6) );
function.set(8, abc);
thread.set(9, abc);
assertEquals(abc, fallback.get(2));
assertEquals(abc, fallback.get(3));
assertEquals(abc, fallback.get(4));
assertEquals(abc, fallback.get(5));
assertEquals(abc, fallback.get(6));
// assertEquals( abc, StringLib.instance.get(7) );
assertEquals( abc, fallback.get(8) );
assertEquals( abc, fallback.get(9) );
assertEquals(abc, fallback.get(8));
assertEquals(abc, fallback.get(9));
// metatable with function call
mt.set( LuaValue.NEWINDEX, new ThreeArgFunction() {
mt.set(LuaValue.NEWINDEX, new ThreeArgFunction() {
public LuaValue call(LuaValue arg1, LuaValue arg2, LuaValue arg3) {
fallback.rawset(arg2, LuaValue.valueOf( "via-func-"+arg3 ));
fallback.rawset(arg2, LuaValue.valueOf("via-func-" + arg3));
return NONE;
}
});
table.set(12,abc);
userdata.set(13,abc);
LuaValue.NIL.set(14,abc);
LuaValue.TRUE.set(15,abc);
LuaValue.ONE.set(16,abc);
table.set(12, abc);
userdata.set(13, abc);
LuaValue.NIL.set(14, abc);
LuaValue.TRUE.set(15, abc);
LuaValue.ONE.set(16, abc);
// string.set(17,abc);
function.set(18,abc);
thread.set(19,abc);
LuaValue via = LuaValue.valueOf( "via-func-abc" );
assertEquals( via, fallback.get(12) );
assertEquals( via, fallback.get(13) );
assertEquals( via, fallback.get(14) );
assertEquals( via, fallback.get(15) );
assertEquals( via, fallback.get(16) );
function.set(18, abc);
thread.set(19, abc);
LuaValue via = LuaValue.valueOf("via-func-abc");
assertEquals(via, fallback.get(12));
assertEquals(via, fallback.get(13));
assertEquals(via, fallback.get(14));
assertEquals(via, fallback.get(15));
assertEquals(via, fallback.get(16));
// assertEquals( via, StringLib.instance.get(17) );
assertEquals( via, fallback.get(18) );
assertEquals( via, fallback.get(19) );
assertEquals(via, fallback.get(18));
assertEquals(via, fallback.get(19));
}
private void checkTable( LuaValue t,
LuaValue aa, LuaValue bb, LuaValue cc, LuaValue dd, LuaValue ee, LuaValue ff, LuaValue gg,
LuaValue ra, LuaValue rb, LuaValue rc, LuaValue rd, LuaValue re, LuaValue rf, LuaValue rg ) {
assertEquals( aa, t.get("aa") );
assertEquals( bb, t.get("bb") );
assertEquals( cc, t.get("cc") );
assertEquals( dd, t.get("dd") );
assertEquals( ee, t.get("ee") );
assertEquals( ff, t.get("ff") );
assertEquals( gg, t.get("gg") );
assertEquals( ra, t.rawget("aa") );
assertEquals( rb, t.rawget("bb") );
assertEquals( rc, t.rawget("cc") );
assertEquals( rd, t.rawget("dd") );
assertEquals( re, t.rawget("ee") );
assertEquals( rf, t.rawget("ff") );
assertEquals( rg, t.rawget("gg") );
private void checkTable(LuaValue t, LuaValue aa, LuaValue bb, LuaValue cc, LuaValue dd, LuaValue ee, LuaValue ff,
LuaValue gg, LuaValue ra, LuaValue rb, LuaValue rc, LuaValue rd, LuaValue re, LuaValue rf, LuaValue rg) {
assertEquals(aa, t.get("aa"));
assertEquals(bb, t.get("bb"));
assertEquals(cc, t.get("cc"));
assertEquals(dd, t.get("dd"));
assertEquals(ee, t.get("ee"));
assertEquals(ff, t.get("ff"));
assertEquals(gg, t.get("gg"));
assertEquals(ra, t.rawget("aa"));
assertEquals(rb, t.rawget("bb"));
assertEquals(rc, t.rawget("cc"));
assertEquals(rd, t.rawget("dd"));
assertEquals(re, t.rawget("ee"));
assertEquals(rf, t.rawget("ff"));
assertEquals(rg, t.rawget("gg"));
}
private LuaValue makeTable( String key1, String val1, String key2, String val2 ) {
return LuaValue.tableOf( new LuaValue[] {
LuaValue.valueOf(key1), LuaValue.valueOf(val1),
LuaValue.valueOf(key2), LuaValue.valueOf(val2),
} );
private LuaValue makeTable(String key1, String val1, String key2, String val2) {
return LuaValue.tableOf(new LuaValue[] { LuaValue.valueOf(key1), LuaValue.valueOf(val1), LuaValue.valueOf(key2),
LuaValue.valueOf(val2), });
}
public void testRawsetMetatableSet() {
// set up tables
LuaValue m = makeTable( "aa", "aaa", "bb", "bbb" );
LuaValue m = makeTable("aa", "aaa", "bb", "bbb");
m.set(LuaValue.INDEX, m);
m.set(LuaValue.NEWINDEX, m);
LuaValue s = makeTable( "cc", "ccc", "dd", "ddd" );
LuaValue t = makeTable( "cc", "ccc", "dd", "ddd" );
LuaValue s = makeTable("cc", "ccc", "dd", "ddd");
LuaValue t = makeTable("cc", "ccc", "dd", "ddd");
t.setmetatable(m);
LuaValue aaa = LuaValue.valueOf("aaa");
LuaValue bbb = LuaValue.valueOf("bbb");
@@ -291,76 +288,75 @@ public class MetatableTest extends TestCase {
LuaValue yyy = LuaValue.valueOf("yyy");
LuaValue zzz = LuaValue.valueOf("zzz");
LuaValue nil = LuaValue.NIL;
// check initial values
// values via "bet()" values via "rawget()"
checkTable( s, nil,nil,ccc,ddd,nil,nil,nil, nil,nil,ccc,ddd,nil,nil,nil );
checkTable( t, aaa,bbb,ccc,ddd,nil,nil,nil, nil,nil,ccc,ddd,nil,nil,nil );
checkTable( m, aaa,bbb,nil,nil,nil,nil,nil, aaa,bbb,nil,nil,nil,nil,nil );
checkTable(s, nil, nil, ccc, ddd, nil, nil, nil, nil, nil, ccc, ddd, nil, nil, nil);
checkTable(t, aaa, bbb, ccc, ddd, nil, nil, nil, nil, nil, ccc, ddd, nil, nil, nil);
checkTable(m, aaa, bbb, nil, nil, nil, nil, nil, aaa, bbb, nil, nil, nil, nil, nil);
// rawset()
s.rawset("aa", www);
checkTable( s, www,nil,ccc,ddd,nil,nil,nil, www,nil,ccc,ddd,nil,nil,nil );
checkTable( t, aaa,bbb,ccc,ddd,nil,nil,nil, nil,nil,ccc,ddd,nil,nil,nil );
checkTable( m, aaa,bbb,nil,nil,nil,nil,nil, aaa,bbb,nil,nil,nil,nil,nil );
checkTable(s, www, nil, ccc, ddd, nil, nil, nil, www, nil, ccc, ddd, nil, nil, nil);
checkTable(t, aaa, bbb, ccc, ddd, nil, nil, nil, nil, nil, ccc, ddd, nil, nil, nil);
checkTable(m, aaa, bbb, nil, nil, nil, nil, nil, aaa, bbb, nil, nil, nil, nil, nil);
s.rawset("cc", xxx);
checkTable( s, www,nil,xxx,ddd,nil,nil,nil, www,nil,xxx,ddd,nil,nil,nil );
checkTable( t, aaa,bbb,ccc,ddd,nil,nil,nil, nil,nil,ccc,ddd,nil,nil,nil );
checkTable( m, aaa,bbb,nil,nil,nil,nil,nil, aaa,bbb,nil,nil,nil,nil,nil );
checkTable(s, www, nil, xxx, ddd, nil, nil, nil, www, nil, xxx, ddd, nil, nil, nil);
checkTable(t, aaa, bbb, ccc, ddd, nil, nil, nil, nil, nil, ccc, ddd, nil, nil, nil);
checkTable(m, aaa, bbb, nil, nil, nil, nil, nil, aaa, bbb, nil, nil, nil, nil, nil);
t.rawset("bb", yyy);
checkTable( s, www,nil,xxx,ddd,nil,nil,nil, www,nil,xxx,ddd,nil,nil,nil );
checkTable( t, aaa,yyy,ccc,ddd,nil,nil,nil, nil,yyy,ccc,ddd,nil,nil,nil );
checkTable( m, aaa,bbb,nil,nil,nil,nil,nil, aaa,bbb,nil,nil,nil,nil,nil );
checkTable(s, www, nil, xxx, ddd, nil, nil, nil, www, nil, xxx, ddd, nil, nil, nil);
checkTable(t, aaa, yyy, ccc, ddd, nil, nil, nil, nil, yyy, ccc, ddd, nil, nil, nil);
checkTable(m, aaa, bbb, nil, nil, nil, nil, nil, aaa, bbb, nil, nil, nil, nil, nil);
t.rawset("dd", zzz);
checkTable( s, www,nil,xxx,ddd,nil,nil,nil, www,nil,xxx,ddd,nil,nil,nil );
checkTable( t, aaa,yyy,ccc,zzz,nil,nil,nil, nil,yyy,ccc,zzz,nil,nil,nil );
checkTable( m, aaa,bbb,nil,nil,nil,nil,nil, aaa,bbb,nil,nil,nil,nil,nil );
checkTable(s, www, nil, xxx, ddd, nil, nil, nil, www, nil, xxx, ddd, nil, nil, nil);
checkTable(t, aaa, yyy, ccc, zzz, nil, nil, nil, nil, yyy, ccc, zzz, nil, nil, nil);
checkTable(m, aaa, bbb, nil, nil, nil, nil, nil, aaa, bbb, nil, nil, nil, nil, nil);
// set() invoking metatables
s.set("ee", ppp);
checkTable( s, www,nil,xxx,ddd,ppp,nil,nil, www,nil,xxx,ddd,ppp,nil,nil );
checkTable( t, aaa,yyy,ccc,zzz,nil,nil,nil, nil,yyy,ccc,zzz,nil,nil,nil );
checkTable( m, aaa,bbb,nil,nil,nil,nil,nil, aaa,bbb,nil,nil,nil,nil,nil );
checkTable(s, www, nil, xxx, ddd, ppp, nil, nil, www, nil, xxx, ddd, ppp, nil, nil);
checkTable(t, aaa, yyy, ccc, zzz, nil, nil, nil, nil, yyy, ccc, zzz, nil, nil, nil);
checkTable(m, aaa, bbb, nil, nil, nil, nil, nil, aaa, bbb, nil, nil, nil, nil, nil);
s.set("cc", qqq);
checkTable( s, www,nil,qqq,ddd,ppp,nil,nil, www,nil,qqq,ddd,ppp,nil,nil );
checkTable( t, aaa,yyy,ccc,zzz,nil,nil,nil, nil,yyy,ccc,zzz,nil,nil,nil );
checkTable( m, aaa,bbb,nil,nil,nil,nil,nil, aaa,bbb,nil,nil,nil,nil,nil );
checkTable(s, www, nil, qqq, ddd, ppp, nil, nil, www, nil, qqq, ddd, ppp, nil, nil);
checkTable(t, aaa, yyy, ccc, zzz, nil, nil, nil, nil, yyy, ccc, zzz, nil, nil, nil);
checkTable(m, aaa, bbb, nil, nil, nil, nil, nil, aaa, bbb, nil, nil, nil, nil, nil);
t.set("ff", rrr);
checkTable( s, www,nil,qqq,ddd,ppp,nil,nil, www,nil,qqq,ddd,ppp,nil,nil );
checkTable( t, aaa,yyy,ccc,zzz,nil,rrr,nil, nil,yyy,ccc,zzz,nil,nil,nil );
checkTable( m, aaa,bbb,nil,nil,nil,rrr,nil, aaa,bbb,nil,nil,nil,rrr,nil );
checkTable(s, www, nil, qqq, ddd, ppp, nil, nil, www, nil, qqq, ddd, ppp, nil, nil);
checkTable(t, aaa, yyy, ccc, zzz, nil, rrr, nil, nil, yyy, ccc, zzz, nil, nil, nil);
checkTable(m, aaa, bbb, nil, nil, nil, rrr, nil, aaa, bbb, nil, nil, nil, rrr, nil);
t.set("dd", sss);
checkTable( s, www,nil,qqq,ddd,ppp,nil,nil, www,nil,qqq,ddd,ppp,nil,nil );
checkTable( t, aaa,yyy,ccc,sss,nil,rrr,nil, nil,yyy,ccc,sss,nil,nil,nil );
checkTable( m, aaa,bbb,nil,nil,nil,rrr,nil, aaa,bbb,nil,nil,nil,rrr,nil );
checkTable(s, www, nil, qqq, ddd, ppp, nil, nil, www, nil, qqq, ddd, ppp, nil, nil);
checkTable(t, aaa, yyy, ccc, sss, nil, rrr, nil, nil, yyy, ccc, sss, nil, nil, nil);
checkTable(m, aaa, bbb, nil, nil, nil, rrr, nil, aaa, bbb, nil, nil, nil, rrr, nil);
m.set("gg", ttt);
checkTable( s, www,nil,qqq,ddd,ppp,nil,nil, www,nil,qqq,ddd,ppp,nil,nil );
checkTable( t, aaa,yyy,ccc,sss,nil,rrr,ttt, nil,yyy,ccc,sss,nil,nil,nil );
checkTable( m, aaa,bbb,nil,nil,nil,rrr,ttt, aaa,bbb,nil,nil,nil,rrr,ttt );
// make s fall back to t
s.setmetatable(LuaValue.tableOf(new LuaValue[] {LuaValue.INDEX,t,LuaValue.NEWINDEX,t}));
checkTable( s, www,yyy,qqq,ddd,ppp,rrr,ttt, www,nil,qqq,ddd,ppp,nil,nil );
checkTable( t, aaa,yyy,ccc,sss,nil,rrr,ttt, nil,yyy,ccc,sss,nil,nil,nil );
checkTable( m, aaa,bbb,nil,nil,nil,rrr,ttt, aaa,bbb,nil,nil,nil,rrr,ttt );
s.set("aa", www);
checkTable( s, www,yyy,qqq,ddd,ppp,rrr,ttt, www,nil,qqq,ddd,ppp,nil,nil );
checkTable( t, aaa,yyy,ccc,sss,nil,rrr,ttt, nil,yyy,ccc,sss,nil,nil,nil );
checkTable( m, aaa,bbb,nil,nil,nil,rrr,ttt, aaa,bbb,nil,nil,nil,rrr,ttt );
s.set("bb", zzz);
checkTable( s, www,zzz,qqq,ddd,ppp,rrr,ttt, www,nil,qqq,ddd,ppp,nil,nil );
checkTable( t, aaa,zzz,ccc,sss,nil,rrr,ttt, nil,zzz,ccc,sss,nil,nil,nil );
checkTable( m, aaa,bbb,nil,nil,nil,rrr,ttt, aaa,bbb,nil,nil,nil,rrr,ttt );
s.set("ee", xxx);
checkTable( s, www,zzz,qqq,ddd,xxx,rrr,ttt, www,nil,qqq,ddd,xxx,nil,nil );
checkTable( t, aaa,zzz,ccc,sss,nil,rrr,ttt, nil,zzz,ccc,sss,nil,nil,nil );
checkTable( m, aaa,bbb,nil,nil,nil,rrr,ttt, aaa,bbb,nil,nil,nil,rrr,ttt );
s.set("ff", yyy);
checkTable( s, www,zzz,qqq,ddd,xxx,yyy,ttt, www,nil,qqq,ddd,xxx,nil,nil );
checkTable( t, aaa,zzz,ccc,sss,nil,yyy,ttt, nil,zzz,ccc,sss,nil,nil,nil );
checkTable( m, aaa,bbb,nil,nil,nil,yyy,ttt, aaa,bbb,nil,nil,nil,yyy,ttt );
checkTable(s, www, nil, qqq, ddd, ppp, nil, nil, www, nil, qqq, ddd, ppp, nil, nil);
checkTable(t, aaa, yyy, ccc, sss, nil, rrr, ttt, nil, yyy, ccc, sss, nil, nil, nil);
checkTable(m, aaa, bbb, nil, nil, nil, rrr, ttt, aaa, bbb, nil, nil, nil, rrr, ttt);
// make s fall back to t
s.setmetatable(LuaValue.tableOf(new LuaValue[] { LuaValue.INDEX, t, LuaValue.NEWINDEX, t }));
checkTable(s, www, yyy, qqq, ddd, ppp, rrr, ttt, www, nil, qqq, ddd, ppp, nil, nil);
checkTable(t, aaa, yyy, ccc, sss, nil, rrr, ttt, nil, yyy, ccc, sss, nil, nil, nil);
checkTable(m, aaa, bbb, nil, nil, nil, rrr, ttt, aaa, bbb, nil, nil, nil, rrr, ttt);
s.set("aa", www);
checkTable(s, www, yyy, qqq, ddd, ppp, rrr, ttt, www, nil, qqq, ddd, ppp, nil, nil);
checkTable(t, aaa, yyy, ccc, sss, nil, rrr, ttt, nil, yyy, ccc, sss, nil, nil, nil);
checkTable(m, aaa, bbb, nil, nil, nil, rrr, ttt, aaa, bbb, nil, nil, nil, rrr, ttt);
s.set("bb", zzz);
checkTable(s, www, zzz, qqq, ddd, ppp, rrr, ttt, www, nil, qqq, ddd, ppp, nil, nil);
checkTable(t, aaa, zzz, ccc, sss, nil, rrr, ttt, nil, zzz, ccc, sss, nil, nil, nil);
checkTable(m, aaa, bbb, nil, nil, nil, rrr, ttt, aaa, bbb, nil, nil, nil, rrr, ttt);
s.set("ee", xxx);
checkTable(s, www, zzz, qqq, ddd, xxx, rrr, ttt, www, nil, qqq, ddd, xxx, nil, nil);
checkTable(t, aaa, zzz, ccc, sss, nil, rrr, ttt, nil, zzz, ccc, sss, nil, nil, nil);
checkTable(m, aaa, bbb, nil, nil, nil, rrr, ttt, aaa, bbb, nil, nil, nil, rrr, ttt);
s.set("ff", yyy);
checkTable(s, www, zzz, qqq, ddd, xxx, yyy, ttt, www, nil, qqq, ddd, xxx, nil, nil);
checkTable(t, aaa, zzz, ccc, sss, nil, yyy, ttt, nil, zzz, ccc, sss, nil, nil, nil);
checkTable(m, aaa, bbb, nil, nil, nil, yyy, ttt, aaa, bbb, nil, nil, nil, yyy, ttt);
}
}

View File

@@ -28,78 +28,59 @@ import junit.framework.TestCase;
import org.luaj.vm2.lib.OneArgFunction;
import org.luaj.vm2.lib.jse.JsePlatform;
public class OrphanedThreadTest extends TestCase {
Globals globals;
LuaThread luathread;
Globals globals;
LuaThread luathread;
WeakReference luathr_ref;
LuaValue function;
LuaValue function;
WeakReference func_ref;
protected void setUp() throws Exception {
LuaThread.thread_orphan_check_interval = 5;
globals = JsePlatform.standardGlobals();
}
protected void tearDown() {
LuaThread.thread_orphan_check_interval = 30000;
}
public void testCollectOrphanedNormalThread() throws Exception {
function = new NormalFunction(globals);
doTest(LuaValue.TRUE, LuaValue.ZERO);
}
public void testCollectOrphanedEarlyCompletionThread() throws Exception {
function = new EarlyCompletionFunction(globals);
doTest(LuaValue.TRUE, LuaValue.ZERO);
}
public void testCollectOrphanedAbnormalThread() throws Exception {
function = new AbnormalFunction(globals);
doTest(LuaValue.FALSE, LuaValue.valueOf("abnormal condition"));
}
public void testCollectOrphanedClosureThread() throws Exception {
String script =
"print('in closure, arg is '..(...))\n" +
"arg = coroutine.yield(1)\n" +
"print('in closure.2, arg is '..arg)\n" +
"arg = coroutine.yield(0)\n" +
"print('leakage in closure.3, arg is '..arg)\n" +
"return 'done'\n";
String script = "print('in closure, arg is '..(...))\n" + "arg = coroutine.yield(1)\n"
+ "print('in closure.2, arg is '..arg)\n" + "arg = coroutine.yield(0)\n"
+ "print('leakage in closure.3, arg is '..arg)\n" + "return 'done'\n";
function = globals.load(script, "script");
doTest(LuaValue.TRUE, LuaValue.ZERO);
}
public void testCollectOrphanedPcallClosureThread() throws Exception {
String script =
"f = function(x)\n" +
" print('in pcall-closure, arg is '..(x))\n" +
" arg = coroutine.yield(1)\n" +
" print('in pcall-closure.2, arg is '..arg)\n" +
" arg = coroutine.yield(0)\n" +
" print('leakage in pcall-closure.3, arg is '..arg)\n" +
" return 'done'\n" +
"end\n" +
"print( 'pcall-closre.result:', pcall( f, ... ) )\n";
String script = "f = function(x)\n" + " print('in pcall-closure, arg is '..(x))\n"
+ " arg = coroutine.yield(1)\n" + " print('in pcall-closure.2, arg is '..arg)\n"
+ " arg = coroutine.yield(0)\n" + " print('leakage in pcall-closure.3, arg is '..arg)\n"
+ " return 'done'\n" + "end\n" + "print( 'pcall-closre.result:', pcall( f, ... ) )\n";
function = globals.load(script, "script");
doTest(LuaValue.TRUE, LuaValue.ZERO);
}
public void testCollectOrphanedLoadCloasureThread() throws Exception {
String script =
"t = { \"print \", \"'hello, \", \"world'\", }\n" +
"i = 0\n" +
"arg = ...\n" +
"f = function()\n" +
" i = i + 1\n" +
" print('in load-closure, arg is', arg, 'next is', t[i])\n" +
" arg = coroutine.yield(1)\n" +
" return t[i]\n" +
"end\n" +
"load(f)()\n";
String script = "t = { \"print \", \"'hello, \", \"world'\", }\n" + "i = 0\n" + "arg = ...\n"
+ "f = function()\n" + " i = i + 1\n" + " print('in load-closure, arg is', arg, 'next is', t[i])\n"
+ " arg = coroutine.yield(1)\n" + " return t[i]\n" + "end\n" + "load(f)()\n";
function = globals.load(script, "script");
doTest(LuaValue.TRUE, LuaValue.ONE);
}
@@ -108,8 +89,8 @@ public class OrphanedThreadTest extends TestCase {
luathread = new LuaThread(globals, function);
luathr_ref = new WeakReference(luathread);
func_ref = new WeakReference(function);
assertNotNull(luathr_ref.get());
assertNotNull(luathr_ref.get());
// resume two times
Varargs a = luathread.resume(LuaValue.valueOf("foo"));
assertEquals(LuaValue.ONE, a.arg(2));
@@ -117,62 +98,67 @@ public class OrphanedThreadTest extends TestCase {
a = luathread.resume(LuaValue.valueOf("bar"));
assertEquals(value2, a.arg(2));
assertEquals(status2, a.arg1());
// drop strong references
luathread = null;
function = null;
// gc
for (int i=0; i<100 && (luathr_ref.get() != null || func_ref.get() != null); i++) {
for (int i = 0; i < 100 && (luathr_ref.get() != null || func_ref.get() != null); i++) {
Runtime.getRuntime().gc();
Thread.sleep(5);
}
// check reference
assertNull(luathr_ref.get());
assertNull(func_ref.get());
}
static class NormalFunction extends OneArgFunction {
final Globals globals;
public NormalFunction(Globals globals) {
this.globals = globals;
}
public LuaValue call(LuaValue arg) {
System.out.println("in normal.1, arg is "+arg);
System.out.println("in normal.1, arg is " + arg);
arg = globals.yield(ONE).arg1();
System.out.println("in normal.2, arg is "+arg);
System.out.println("in normal.2, arg is " + arg);
arg = globals.yield(ZERO).arg1();
System.out.println("in normal.3, arg is "+arg);
System.out.println("in normal.3, arg is " + arg);
return NONE;
}
}
}
static class EarlyCompletionFunction extends OneArgFunction {
final Globals globals;
public EarlyCompletionFunction(Globals globals) {
this.globals = globals;
}
public LuaValue call(LuaValue arg) {
System.out.println("in early.1, arg is "+arg);
System.out.println("in early.1, arg is " + arg);
arg = globals.yield(ONE).arg1();
System.out.println("in early.2, arg is "+arg);
System.out.println("in early.2, arg is " + arg);
return ZERO;
}
}
}
static class AbnormalFunction extends OneArgFunction {
final Globals globals;
public AbnormalFunction(Globals globals) {
this.globals = globals;
}
public LuaValue call(LuaValue arg) {
System.out.println("in abnormal.1, arg is "+arg);
System.out.println("in abnormal.1, arg is " + arg);
arg = globals.yield(ONE).arg1();
System.out.println("in abnormal.2, arg is "+arg);
System.out.println("in abnormal.2, arg is " + arg);
error("abnormal condition");
return ZERO;
}
}
}
}

View File

@@ -11,7 +11,7 @@ public class RequireClassTest extends TestCase {
private LuaTable globals;
private LuaValue require;
public void setUp() {
globals = JsePlatform.standardGlobals();
require = globals.get("require");
@@ -19,71 +19,65 @@ public class RequireClassTest extends TestCase {
public void testLoadClass() {
LuaValue result = globals.load(new org.luaj.vm2.require.RequireSampleSuccess());
assertEquals( "require-sample-success-", result.tojstring() );
assertEquals("require-sample-success-", result.tojstring());
}
public void testRequireClassSuccess() {
LuaValue result = require.call( LuaValue.valueOf("org.luaj.vm2.require.RequireSampleSuccess") );
assertEquals( "require-sample-success-org.luaj.vm2.require.RequireSampleSuccess", result.tojstring() );
result = require.call( LuaValue.valueOf("org.luaj.vm2.require.RequireSampleSuccess") );
assertEquals( "require-sample-success-org.luaj.vm2.require.RequireSampleSuccess", result.tojstring() );
LuaValue result = require.call(LuaValue.valueOf("org.luaj.vm2.require.RequireSampleSuccess"));
assertEquals("require-sample-success-org.luaj.vm2.require.RequireSampleSuccess", result.tojstring());
result = require.call(LuaValue.valueOf("org.luaj.vm2.require.RequireSampleSuccess"));
assertEquals("require-sample-success-org.luaj.vm2.require.RequireSampleSuccess", result.tojstring());
}
public void testRequireClassLoadLuaError() {
try {
LuaValue result = require.call( LuaValue.valueOf(RequireSampleLoadLuaError.class.getName()) );
fail( "incorrectly loaded class that threw lua error");
} catch ( LuaError le ) {
assertEquals(
"sample-load-lua-error",
le.getMessage() );
LuaValue result = require.call(LuaValue.valueOf(RequireSampleLoadLuaError.class.getName()));
fail("incorrectly loaded class that threw lua error");
} catch (LuaError le) {
assertEquals("sample-load-lua-error", le.getMessage());
}
try {
LuaValue result = require.call( LuaValue.valueOf(RequireSampleLoadLuaError.class.getName()) );
fail( "incorrectly loaded class that threw lua error");
} catch ( LuaError le ) {
assertEquals(
"loop or previous error loading module '"+RequireSampleLoadLuaError.class.getName()+"'",
le.getMessage() );
LuaValue result = require.call(LuaValue.valueOf(RequireSampleLoadLuaError.class.getName()));
fail("incorrectly loaded class that threw lua error");
} catch (LuaError le) {
assertEquals("loop or previous error loading module '" + RequireSampleLoadLuaError.class.getName() + "'",
le.getMessage());
}
}
public void testRequireClassLoadRuntimeException() {
try {
LuaValue result = require.call( LuaValue.valueOf(RequireSampleLoadRuntimeExcep.class.getName()) );
fail( "incorrectly loaded class that threw runtime exception");
} catch ( RuntimeException le ) {
assertEquals(
"sample-load-runtime-exception",
le.getMessage() );
LuaValue result = require.call(LuaValue.valueOf(RequireSampleLoadRuntimeExcep.class.getName()));
fail("incorrectly loaded class that threw runtime exception");
} catch (RuntimeException le) {
assertEquals("sample-load-runtime-exception", le.getMessage());
}
try {
LuaValue result = require.call( LuaValue.valueOf(RequireSampleLoadRuntimeExcep.class.getName()) );
fail( "incorrectly loaded class that threw runtime exception");
} catch ( LuaError le ) {
assertEquals(
"loop or previous error loading module '"+RequireSampleLoadRuntimeExcep.class.getName()+"'",
le.getMessage() );
LuaValue result = require.call(LuaValue.valueOf(RequireSampleLoadRuntimeExcep.class.getName()));
fail("incorrectly loaded class that threw runtime exception");
} catch (LuaError le) {
assertEquals(
"loop or previous error loading module '" + RequireSampleLoadRuntimeExcep.class.getName() + "'",
le.getMessage());
}
}
public void testRequireClassClassCastException() {
try {
LuaValue result = require.call( LuaValue.valueOf(RequireSampleClassCastExcep.class.getName()) );
fail( "incorrectly loaded class that threw class cast exception");
} catch ( LuaError le ) {
LuaValue result = require.call(LuaValue.valueOf(RequireSampleClassCastExcep.class.getName()));
fail("incorrectly loaded class that threw class cast exception");
} catch (LuaError le) {
String msg = le.getMessage();
if ( msg.indexOf("not found") < 0 )
fail( "expected 'not found' message but got "+msg );
if (msg.indexOf("not found") < 0)
fail("expected 'not found' message but got " + msg);
}
try {
LuaValue result = require.call( LuaValue.valueOf(RequireSampleClassCastExcep.class.getName()) );
fail( "incorrectly loaded class that threw class cast exception");
} catch ( LuaError le ) {
LuaValue result = require.call(LuaValue.valueOf(RequireSampleClassCastExcep.class.getName()));
fail("incorrectly loaded class that threw class cast exception");
} catch (LuaError le) {
String msg = le.getMessage();
if ( msg.indexOf("not found") < 0 )
fail( "expected 'not found' message but got "+msg );
if (msg.indexOf("not found") < 0)
fail("expected 'not found' message but got " + msg);
}
}
}

View File

@@ -38,29 +38,28 @@ import org.luaj.vm2.lib.ResourceFinder;
import org.luaj.vm2.lib.jse.JseProcess;
import org.luaj.vm2.luajc.LuaJC;
abstract
public class ScriptDrivenTest extends TestCase implements ResourceFinder {
abstract public class ScriptDrivenTest extends TestCase implements ResourceFinder {
public static final boolean nocompile = "true".equals(System.getProperty("nocompile"));
public enum PlatformType {
JME, JSE, LUAJIT,
}
private final PlatformType platform;
private final String subdir;
protected Globals globals;
static final String zipdir = "test/lua/";
private final String subdir;
protected Globals globals;
static final String zipdir = "test/lua/";
static final String zipfile = "luaj3.0-tests.zip";
protected ScriptDrivenTest( PlatformType platform, String subdir ) {
protected ScriptDrivenTest(PlatformType platform, String subdir) {
this.platform = platform;
this.subdir = subdir;
initGlobals();
}
private void initGlobals() {
switch ( platform ) {
switch (platform) {
default:
case JSE:
case LUAJIT:
@@ -71,8 +70,7 @@ public class ScriptDrivenTest extends TestCase implements ResourceFinder {
break;
}
}
protected void setUp() throws Exception {
super.setUp();
initGlobals();
@@ -82,21 +80,26 @@ public class ScriptDrivenTest extends TestCase implements ResourceFinder {
// ResourceFinder implementation.
public InputStream findResource(String filename) {
InputStream is = findInPlainFile(filename);
if (is != null) return is;
is = findInPlainFileAsResource("",filename);
if (is != null) return is;
is = findInPlainFileAsResource("/",filename);
if (is != null) return is;
if (is != null)
return is;
is = findInPlainFileAsResource("", filename);
if (is != null)
return is;
is = findInPlainFileAsResource("/", filename);
if (is != null)
return is;
is = findInZipFileAsPlainFile(filename);
if (is != null) return is;
is = findInZipFileAsResource("",filename);
if (is != null) return is;
is = findInZipFileAsResource("/",filename);
if (is != null)
return is;
is = findInZipFileAsResource("", filename);
if (is != null)
return is;
is = findInZipFileAsResource("/", filename);
return is;
}
private InputStream findInPlainFileAsResource(String prefix, String filename) {
return getClass().getResourceAsStream(prefix + subdir + filename);
return getClass().getResourceAsStream(prefix+subdir+filename);
}
private InputStream findInPlainFile(String filename) {
@@ -104,7 +107,7 @@ public class ScriptDrivenTest extends TestCase implements ResourceFinder {
File f = new File(zipdir+subdir+filename);
if (f.exists())
return new FileInputStream(f);
} catch ( IOException ioe ) {
} catch (IOException ioe) {
ioe.printStackTrace();
}
return null;
@@ -112,14 +115,14 @@ public class ScriptDrivenTest extends TestCase implements ResourceFinder {
private InputStream findInZipFileAsPlainFile(String filename) {
URL zip;
File file = new File(zipdir+zipfile);
File file = new File(zipdir+zipfile);
try {
if ( file.exists() ) {
if (file.exists()) {
zip = file.toURI().toURL();
String path = "jar:"+zip.toExternalForm()+ "!/"+subdir+filename;
String path = "jar:" + zip.toExternalForm() + "!/" + subdir + filename;
URL url = new URL(path);
return url.openStream();
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
@@ -130,13 +133,12 @@ public class ScriptDrivenTest extends TestCase implements ResourceFinder {
return null;
}
private InputStream findInZipFileAsResource(String prefix, String filename) {
URL zip = null;
URL zip = null;
zip = getClass().getResource(zipfile);
if ( zip != null )
if (zip != null)
try {
String path = "jar:"+zip.toExternalForm()+ "!/"+subdir+filename;
String path = "jar:" + zip.toExternalForm() + "!/" + subdir + filename;
URL url = new URL(path);
return url.openStream();
} catch (IOException ioe) {
@@ -144,47 +146,47 @@ public class ScriptDrivenTest extends TestCase implements ResourceFinder {
}
return null;
}
// */
protected void runTest(String testName) {
try {
// override print()
final ByteArrayOutputStream output = new ByteArrayOutputStream();
final PrintStream oldps = globals.STDOUT;
final PrintStream ps = new PrintStream( output );
final PrintStream ps = new PrintStream(output);
globals.STDOUT = ps;
// run the script
try {
LuaValue chunk = loadScript(testName, globals);
chunk.call(LuaValue.valueOf(platform.toString()));
ps.flush();
String actualOutput = new String(output.toByteArray());
String expectedOutput = getExpectedOutput(testName);
actualOutput = actualOutput.replaceAll("\r\n", "\n");
expectedOutput = expectedOutput.replaceAll("\r\n", "\n");
assertEquals(expectedOutput, actualOutput);
} finally {
globals.STDOUT = oldps;
ps.close();
}
} catch ( IOException ioe ) {
} catch (IOException ioe) {
throw new RuntimeException(ioe.toString());
} catch ( InterruptedException ie ) {
} catch (InterruptedException ie) {
throw new RuntimeException(ie.toString());
}
}
protected LuaValue loadScript(String name, Globals globals) throws IOException {
InputStream script = this.findResource(name+".lua");
if ( script == null )
InputStream script = this.findResource(name + ".lua");
if (script == null)
fail("Could not load script for test case: " + name);
try {
switch ( this.platform ) {
switch (this.platform) {
case LUAJIT:
if ( nocompile ) {
if (nocompile) {
LuaValue c = (LuaValue) Class.forName(name).newInstance();
return c;
} else {
@@ -192,48 +194,47 @@ public class ScriptDrivenTest extends TestCase implements ResourceFinder {
return globals.load(script, name, "bt", globals);
}
default:
return globals.load(script, "@"+name+".lua", "bt", globals);
return globals.load(script, "@" + name + ".lua", "bt", globals);
}
} catch ( Exception e ) {
} catch (Exception e) {
e.printStackTrace();
throw new IOException( e.toString() );
throw new IOException(e.toString());
} finally {
script.close();
}
}
private String getExpectedOutput(final String name) throws IOException,
InterruptedException {
InputStream output = this.findResource(name+".out");
private String getExpectedOutput(final String name) throws IOException, InterruptedException {
InputStream output = this.findResource(name + ".out");
if (output != null)
try {
return readString(output);
} finally {
output.close();
}
String expectedOutput = executeLuaProcess(name);
if (expectedOutput == null)
throw new IOException("Failed to get comparison output or run process for "+name);
return expectedOutput;
String expectedOutput = executeLuaProcess(name);
if (expectedOutput == null)
throw new IOException("Failed to get comparison output or run process for " + name);
return expectedOutput;
}
private String executeLuaProcess(String name) throws IOException, InterruptedException {
InputStream script = findResource(name+".lua");
if ( script == null )
throw new IOException("Failed to find source file "+script);
InputStream script = findResource(name + ".lua");
if (script == null)
throw new IOException("Failed to find source file " + script);
try {
String luaCommand = System.getProperty("LUA_COMMAND");
if ( luaCommand == null )
luaCommand = "lua";
String[] args = new String[] { luaCommand, "-", platform.toString() };
String luaCommand = System.getProperty("LUA_COMMAND");
if (luaCommand == null)
luaCommand = "lua";
String[] args = new String[] { luaCommand, "-", platform.toString() };
return collectProcessOutput(args, script);
} finally {
script.close();
}
}
public static String collectProcessOutput(String[] cmd, final InputStream input)
throws IOException, InterruptedException {
throws IOException, InterruptedException {
Runtime r = Runtime.getRuntime();
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
new JseProcess(cmd, input, baos, System.err).waitFor();
@@ -249,7 +250,7 @@ public class ScriptDrivenTest extends TestCase implements ResourceFinder {
private static void copy(InputStream is, OutputStream os) throws IOException {
byte[] buf = new byte[1024];
int r;
while ((r = is.read(buf)) >= 0) {
while ( (r = is.read(buf)) >= 0 ) {
os.write(buf, 0, r);
}
}

View File

@@ -16,52 +16,51 @@ public class StringTest extends TestCase {
public void testToInputStream() throws IOException {
LuaString str = LuaString.valueOf("Hello");
InputStream is = str.toInputStream();
assertEquals( 'H', is.read() );
assertEquals( 'e', is.read() );
assertEquals( 2, is.skip( 2 ) );
assertEquals( 'o', is.read() );
assertEquals( -1, is.read() );
assertTrue( is.markSupported() );
assertEquals('H', is.read());
assertEquals('e', is.read());
assertEquals(2, is.skip(2));
assertEquals('o', is.read());
assertEquals(-1, is.read());
assertTrue(is.markSupported());
is.reset();
assertEquals( 'H', is.read() );
is.mark( 4 );
assertEquals( 'e', is.read() );
assertEquals('H', is.read());
is.mark(4);
assertEquals('e', is.read());
is.reset();
assertEquals( 'e', is.read() );
LuaString substr = str.substring( 1, 4 );
assertEquals( 3, substr.length() );
assertEquals('e', is.read());
LuaString substr = str.substring(1, 4);
assertEquals(3, substr.length());
is.close();
is = substr.toInputStream();
assertEquals( 'e', is.read() );
assertEquals( 'l', is.read() );
assertEquals( 'l', is.read() );
assertEquals( -1, is.read() );
assertEquals('e', is.read());
assertEquals('l', is.read());
assertEquals('l', is.read());
assertEquals(-1, is.read());
is = substr.toInputStream();
is.reset();
assertEquals( 'e', is.read() );
assertEquals('e', is.read());
}
private static final String userFriendly( String s ) {
private static final String userFriendly(String s) {
StringBuffer sb = new StringBuffer();
for ( int i=0, n=s.length(); i<n; i++ ) {
for (int i = 0, n = s.length(); i < n; i++) {
int c = s.charAt(i);
if ( c < ' ' || c >= 0x80 ) {
sb.append( "\\u"+Integer.toHexString(0x10000+c).substring(1) );
if (c < ' ' || c >= 0x80) {
sb.append("\\u" + Integer.toHexString(0x10000+c).substring(1));
} else {
sb.append( (char) c );
sb.append((char) c);
}
}
return sb.toString();
@@ -70,29 +69,30 @@ public class StringTest extends TestCase {
public void testUtf820482051() throws UnsupportedEncodingException {
int i = 2048;
char[] c = { (char) (i+0), (char) (i+1), (char) (i+2), (char) (i+3) };
String before = new String(c)+" "+i+"-"+(i+4);
String before = new String(c) + " " + i + "-" + (i+4);
LuaString ls = LuaString.valueOf(before);
String after = ls.tojstring();
assertEquals( userFriendly( before ), userFriendly( after ) );
assertEquals(userFriendly(before), userFriendly(after));
}
public void testUtf8() {
for ( int i=4; i<0xffff; i+=4 ) {
public void testUtf8() {
for (int i = 4; i < 0xffff; i += 4) {
char[] c = { (char) (i+0), (char) (i+1), (char) (i+2), (char) (i+3) };
String before = new String(c)+" "+i+"-"+(i+4);
String before = new String(c) + " " + i + "-" + (i+4);
LuaString ls = LuaString.valueOf(before);
String after = ls.tojstring();
assertEquals( userFriendly( before ), userFriendly( after ) );
assertEquals(userFriendly(before), userFriendly(after));
}
char[] c = { (char) (1), (char) (2), (char) (3) };
String before = new String(c)+" 1-3";
String before = new String(c) + " 1-3";
LuaString ls = LuaString.valueOf(before);
String after = ls.tojstring();
assertEquals( userFriendly( before ), userFriendly( after ) );
assertEquals(userFriendly(before), userFriendly(after));
}
public void testSpotCheckUtf8() throws UnsupportedEncodingException {
byte[] bytes = {(byte)194,(byte)160,(byte)194,(byte)161,(byte)194,(byte)162,(byte)194,(byte)163,(byte)194,(byte)164};
byte[] bytes = { (byte) 194, (byte) 160, (byte) 194, (byte) 161, (byte) 194, (byte) 162, (byte) 194, (byte) 163,
(byte) 194, (byte) 164 };
String expected = new String(bytes, "UTF8");
String actual = LuaString.valueOf(bytes).tojstring();
char[] d = actual.toCharArray();
@@ -103,37 +103,37 @@ public class StringTest extends TestCase {
assertEquals(164, d[4]);
assertEquals(expected, actual);
}
public void testNullTerminated() {
public void testNullTerminated() {
char[] c = { 'a', 'b', 'c', '\0', 'd', 'e', 'f' };
String before = new String(c);
LuaString ls = LuaString.valueOf(before);
String after = ls.tojstring();
assertEquals( userFriendly( "abc\0def" ), userFriendly( after ) );
assertEquals(userFriendly("abc\0def"), userFriendly(after));
}
public void testRecentStringsCacheDifferentHashcodes() {
final byte[] abc = {'a', 'b', 'c' };
final byte[] xyz = {'x', 'y', 'z' };
final byte[] abc = { 'a', 'b', 'c' };
final byte[] xyz = { 'x', 'y', 'z' };
final LuaString abc1 = LuaString.valueOf(abc);
final LuaString xyz1 = LuaString.valueOf(xyz);
final LuaString abc2 = LuaString.valueOf(abc);
final LuaString xyz2 = LuaString.valueOf(xyz);
final int mod = LuaString.RECENT_STRINGS_CACHE_SIZE;
assertTrue(abc1.hashCode() % mod != xyz1.hashCode() % mod);
assertTrue(abc1.hashCode()%mod != xyz1.hashCode()%mod);
assertSame(abc1, abc2);
assertSame(xyz1, xyz2);
}
public void testRecentStringsCacheHashCollisionCacheHit() {
final byte[] abc = {'a', 'b', 'c' };
final byte[] lyz = {'l', 'y', 'z' }; // chosen to have hash collision with 'abc'
final byte[] abc = { 'a', 'b', 'c' };
final byte[] lyz = { 'l', 'y', 'z' }; // chosen to have hash collision with 'abc'
final LuaString abc1 = LuaString.valueOf(abc);
final LuaString abc2 = LuaString.valueOf(abc); // in cache: 'abc'
final LuaString lyz1 = LuaString.valueOf(lyz);
final LuaString lyz2 = LuaString.valueOf(lyz); // in cache: 'lyz'
final int mod = LuaString.RECENT_STRINGS_CACHE_SIZE;
assertEquals(abc1.hashCode() % mod, lyz1.hashCode() % mod);
assertEquals(abc1.hashCode()%mod, lyz1.hashCode()%mod);
assertNotSame(abc1, lyz1);
assertFalse(abc1.equals(lyz1));
assertSame(abc1, abc2);
@@ -141,14 +141,14 @@ public class StringTest extends TestCase {
}
public void testRecentStringsCacheHashCollisionCacheMiss() {
final byte[] abc = {'a', 'b', 'c' };
final byte[] lyz = {'l', 'y', 'z' }; // chosen to have hash collision with 'abc'
final byte[] abc = { 'a', 'b', 'c' };
final byte[] lyz = { 'l', 'y', 'z' }; // chosen to have hash collision with 'abc'
final LuaString abc1 = LuaString.valueOf(abc);
final LuaString lyz1 = LuaString.valueOf(lyz); // in cache: 'abc'
final LuaString abc2 = LuaString.valueOf(abc); // in cache: 'lyz'
final LuaString lyz2 = LuaString.valueOf(lyz); // in cache: 'abc'
final int mod = LuaString.RECENT_STRINGS_CACHE_SIZE;
assertEquals(abc1.hashCode() % mod, lyz1.hashCode() % mod);
assertEquals(abc1.hashCode()%mod, lyz1.hashCode()%mod);
assertNotSame(abc1, lyz1);
assertFalse(abc1.equals(lyz1));
assertNotSame(abc1, abc2);
@@ -165,7 +165,7 @@ public class StringTest extends TestCase {
public void testRecentStringsUsingJavaStrings() {
final String abc = "abc";
final String lyz = "lyz"; // chosen to have hash collision with 'abc'
final String lyz = "lyz"; // chosen to have hash collision with 'abc'
final String xyz = "xyz";
final LuaString abc1 = LuaString.valueOf(abc);
@@ -175,8 +175,8 @@ public class StringTest extends TestCase {
final LuaString xyz1 = LuaString.valueOf(xyz);
final LuaString xyz2 = LuaString.valueOf(xyz);
final int mod = LuaString.RECENT_STRINGS_CACHE_SIZE;
assertEquals(abc1.hashCode() % mod, lyz1.hashCode() % mod);
assertFalse(abc1.hashCode() % mod == xyz1.hashCode() % mod);
assertEquals(abc1.hashCode()%mod, lyz1.hashCode()%mod);
assertFalse(abc1.hashCode()%mod == xyz1.hashCode()%mod);
assertSame(abc1, abc2);
assertSame(lyz1, lyz2);
assertSame(xyz1, xyz2);
@@ -188,11 +188,11 @@ public class StringTest extends TestCase {
final LuaString abc4 = LuaString.valueOf(abc);
final LuaString lyz4 = LuaString.valueOf(lyz);
final LuaString xyz4 = LuaString.valueOf(xyz);
assertNotSame(abc3, abc4); // because of hash collision
assertNotSame(lyz3, lyz4); // because of hash collision
assertSame(xyz3, xyz4); // because hashes do not collide
assertNotSame(abc3, abc4); // because of hash collision
assertNotSame(lyz3, lyz4); // because of hash collision
assertSame(xyz3, xyz4); // because hashes do not collide
}
public void testLongSubstringGetsOldBacking() {
LuaString src = LuaString.valueOf("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
LuaString sub1 = src.substring(10, 40);
@@ -200,7 +200,7 @@ public class StringTest extends TestCase {
assertEquals(sub1.m_offset, 10);
assertEquals(sub1.m_length, 30);
}
public void testShortSubstringGetsNewBacking() {
LuaString src = LuaString.valueOf("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
LuaString sub1 = src.substring(10, 20);
@@ -210,11 +210,10 @@ public class StringTest extends TestCase {
assertSame(sub1, sub2);
assertFalse(src.m_bytes == sub1.m_bytes);
}
public void testShortSubstringOfVeryLongStringGetsNewBacking() {
LuaString src = LuaString.valueOf(
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" +
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" );
LuaString src = LuaString.valueOf("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
+ "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
LuaString sub1 = src.substring(10, 50);
LuaString sub2 = src.substring(10, 50);
assertEquals(sub1.m_offset, 0);
@@ -230,7 +229,7 @@ public class StringTest extends TestCase {
assertEquals(8, sub.m_length);
assertEquals(0, str.m_offset);
assertEquals(2, sub.m_offset);
assertEquals(6, str.indexOf((byte) ':', 0));
assertEquals(6, str.indexOf((byte) ':', 2));
assertEquals(6, str.indexOf((byte) ':', 6));
@@ -267,7 +266,7 @@ public class StringTest extends TestCase {
LuaString pat = LuaString.valueOf(":");
LuaString i = LuaString.valueOf("i");
LuaString xyz = LuaString.valueOf("xyz");
assertEquals(6, str.indexOf(pat, 0));
assertEquals(6, str.indexOf(pat, 2));
assertEquals(6, str.indexOf(pat, 6));
@@ -304,7 +303,7 @@ public class StringTest extends TestCase {
LuaString pat = LuaString.valueOf(":");
LuaString i = LuaString.valueOf("i");
LuaString xyz = LuaString.valueOf("xyz");
assertEquals(6, str.lastIndexOf(pat));
assertEquals(9, str.lastIndexOf(i));
assertEquals(-1, str.lastIndexOf(xyz));
@@ -325,14 +324,14 @@ public class StringTest extends TestCase {
LuaString ghi = LuaString.valueOf("ghi");
LuaString ihg = LuaString.valueOf("ihg");
LuaString ijk = LuaString.valueOf("ijk");
LuaString kji= LuaString.valueOf("kji");
LuaString kji = LuaString.valueOf("kji");
LuaString xyz = LuaString.valueOf("xyz");
LuaString ABCdEFGHIJKL = LuaString.valueOf("ABCdEFGHIJKL");
LuaString EFGHIJKL = ABCdEFGHIJKL.substring(4, 12);
LuaString CdEFGHIJ = ABCdEFGHIJKL.substring(2, 10);
assertEquals(4, EFGHIJKL.m_offset);
assertEquals(2, CdEFGHIJ.m_offset);
assertEquals(7, str.indexOfAny(ghi));
assertEquals(7, str.indexOfAny(ihg));
assertEquals(9, str.indexOfAny(ijk));
@@ -349,7 +348,7 @@ public class StringTest extends TestCase {
assertEquals(1, sub.indexOfAny(CdEFGHIJ));
assertEquals(-1, sub.indexOfAny(EFGHIJKL));
}
public void testMatchShortPatterns() {
LuaValue[] args = { LuaString.valueOf("%bxy") };
LuaString _ = LuaString.valueOf("");
@@ -363,7 +362,7 @@ public class StringTest extends TestCase {
LuaString xby = LuaString.valueOf("xby");
LuaString axbya = LuaString.valueOf("axbya");
LuaValue nil = LuaValue.NIL;
assertEquals(nil, _.invokemethod("match", args));
assertEquals(nil, a.invokemethod("match", args));
assertEquals(nil, ax.invokemethod("match", args));
@@ -373,9 +372,9 @@ public class StringTest extends TestCase {
assertEquals(nil, bya.invokemethod("match", args));
assertEquals(xby, xby.invokemethod("match", args));
assertEquals(xby, axbya.invokemethod("match", args));
assertEquals(xby, axbya.substring(0,4).invokemethod("match", args));
assertEquals(nil, axbya.substring(0,3).invokemethod("match", args));
assertEquals(xby, axbya.substring(1,5).invokemethod("match", args));
assertEquals(nil, axbya.substring(2,5).invokemethod("match", args));
assertEquals(xby, axbya.substring(0, 4).invokemethod("match", args));
assertEquals(nil, axbya.substring(0, 3).invokemethod("match", args));
assertEquals(xby, axbya.substring(1, 5).invokemethod("match", args));
assertEquals(nil, axbya.substring(2, 5).invokemethod("match", args));
}
}

View File

@@ -29,239 +29,238 @@ import org.luaj.vm2.LuaValue;
import org.luaj.vm2.lib.TwoArgFunction;
/**
* Tests for tables used as lists.
* Tests for tables used as lists.
*/
public class TableHashTest extends TestCase {
protected LuaTable new_Table() {
return new LuaTable();
}
protected LuaTable new_Table(int n,int m) {
return new LuaTable(n,m);
protected LuaTable new_Table(int n, int m) {
return new LuaTable(n, m);
}
public void testSetRemove() {
LuaTable t = new_Table();
assertEquals( 0, t.getHashLength() );
assertEquals( 0, t.length() );
assertEquals( 0, t.keyCount() );
String[] keys = { "abc", "def", "ghi", "jkl", "mno", "pqr", "stu", "wxy", "z01",
"cd", "ef", "g", "hi", "jk", "lm", "no", "pq", "rs", };
assertEquals(0, t.getHashLength());
assertEquals(0, t.length());
assertEquals(0, t.keyCount());
String[] keys = { "abc", "def", "ghi", "jkl", "mno", "pqr", "stu", "wxy", "z01", "cd", "ef", "g", "hi", "jk",
"lm", "no", "pq", "rs", };
int[] capacities = { 0, 2, 2, 4, 4, 8, 8, 8, 8, 16, 16, 16, 16, 16, 16, 16, 16, 32, 32, 32 };
for ( int i = 0; i < keys.length; ++i ) {
assertEquals( capacities[i], t.getHashLength() );
String si = "Test Value! "+i;
t.set( keys[i], si );
assertEquals( 0, t.length() );
assertEquals( i+1, t.keyCount() );
for (int i = 0; i < keys.length; ++i) {
assertEquals(capacities[i], t.getHashLength());
String si = "Test Value! " + i;
t.set(keys[i], si);
assertEquals(0, t.length());
assertEquals(i+1, t.keyCount());
}
assertEquals( capacities[keys.length], t.getHashLength() );
for ( int i = 0; i < keys.length; ++i ) {
LuaValue vi = LuaString.valueOf( "Test Value! "+i );
assertEquals( vi, t.get( keys[i] ) );
assertEquals( vi, t.get( LuaString.valueOf(keys[i]) ) );
assertEquals( vi, t.rawget( keys[i] ) );
assertEquals( vi, t.rawget( keys[i] ) );
assertEquals(capacities[keys.length], t.getHashLength());
for (int i = 0; i < keys.length; ++i) {
LuaValue vi = LuaString.valueOf("Test Value! " + i);
assertEquals(vi, t.get(keys[i]));
assertEquals(vi, t.get(LuaString.valueOf(keys[i])));
assertEquals(vi, t.rawget(keys[i]));
assertEquals(vi, t.rawget(keys[i]));
}
// replace with new values
for ( int i = 0; i < keys.length; ++i ) {
t.set( keys[i], LuaString.valueOf( "Replacement Value! "+i ) );
assertEquals( 0, t.length() );
assertEquals( keys.length, t.keyCount() );
assertEquals( capacities[keys.length], t.getHashLength() );
for (int i = 0; i < keys.length; ++i) {
t.set(keys[i], LuaString.valueOf("Replacement Value! " + i));
assertEquals(0, t.length());
assertEquals(keys.length, t.keyCount());
assertEquals(capacities[keys.length], t.getHashLength());
}
for ( int i = 0; i < keys.length; ++i ) {
LuaValue vi = LuaString.valueOf( "Replacement Value! "+i );
assertEquals( vi, t.get( keys[i] ) );
for (int i = 0; i < keys.length; ++i) {
LuaValue vi = LuaString.valueOf("Replacement Value! " + i);
assertEquals(vi, t.get(keys[i]));
}
// remove
for ( int i = 0; i < keys.length; ++i ) {
t.set( keys[i], LuaValue.NIL );
assertEquals( 0, t.length() );
assertEquals( keys.length-i-1, t.keyCount() );
if ( i<keys.length-1 )
assertEquals( capacities[keys.length], t.getHashLength() );
for (int i = 0; i < keys.length; ++i) {
t.set(keys[i], LuaValue.NIL);
assertEquals(0, t.length());
assertEquals(keys.length-i-1, t.keyCount());
if (i < keys.length-1)
assertEquals(capacities[keys.length], t.getHashLength());
else
assertTrue( 0<=t.getHashLength() );
assertTrue(0 <= t.getHashLength());
}
for ( int i = 0; i < keys.length; ++i ) {
assertEquals( LuaValue.NIL, t.get( keys[i] ) );
for (int i = 0; i < keys.length; ++i) {
assertEquals(LuaValue.NIL, t.get(keys[i]));
}
}
public void testIndexMetatag() {
LuaTable t = new_Table();
LuaTable mt = new_Table();
LuaTable fb = new_Table();
// set basic values
t.set( "ppp", "abc" );
t.set( 123, "def" );
t.set("ppp", "abc");
t.set(123, "def");
mt.set(LuaValue.INDEX, fb);
fb.set( "qqq", "ghi" );
fb.set( 456, "jkl" );
fb.set("qqq", "ghi");
fb.set(456, "jkl");
// check before setting metatable
assertEquals( "abc", t.get("ppp").tojstring() );
assertEquals( "def", t.get(123).tojstring() );
assertEquals( "nil", t.get("qqq").tojstring() );
assertEquals( "nil", t.get(456).tojstring() );
assertEquals( "nil", fb.get("ppp").tojstring() );
assertEquals( "nil", fb.get(123).tojstring() );
assertEquals( "ghi", fb.get("qqq").tojstring() );
assertEquals( "jkl", fb.get(456).tojstring() );
assertEquals( "nil", mt.get("ppp").tojstring() );
assertEquals( "nil", mt.get(123).tojstring() );
assertEquals( "nil", mt.get("qqq").tojstring() );
assertEquals( "nil", mt.get(456).tojstring() );
assertEquals("abc", t.get("ppp").tojstring());
assertEquals("def", t.get(123).tojstring());
assertEquals("nil", t.get("qqq").tojstring());
assertEquals("nil", t.get(456).tojstring());
assertEquals("nil", fb.get("ppp").tojstring());
assertEquals("nil", fb.get(123).tojstring());
assertEquals("ghi", fb.get("qqq").tojstring());
assertEquals("jkl", fb.get(456).tojstring());
assertEquals("nil", mt.get("ppp").tojstring());
assertEquals("nil", mt.get(123).tojstring());
assertEquals("nil", mt.get("qqq").tojstring());
assertEquals("nil", mt.get(456).tojstring());
// check before setting metatable
t.setmetatable(mt);
assertEquals( mt, t.getmetatable() );
assertEquals( "abc", t.get("ppp").tojstring() );
assertEquals( "def", t.get(123).tojstring() );
assertEquals( "ghi", t.get("qqq").tojstring() );
assertEquals( "jkl", t.get(456).tojstring() );
assertEquals( "nil", fb.get("ppp").tojstring() );
assertEquals( "nil", fb.get(123).tojstring() );
assertEquals( "ghi", fb.get("qqq").tojstring() );
assertEquals( "jkl", fb.get(456).tojstring() );
assertEquals( "nil", mt.get("ppp").tojstring() );
assertEquals( "nil", mt.get(123).tojstring() );
assertEquals( "nil", mt.get("qqq").tojstring() );
assertEquals( "nil", mt.get(456).tojstring() );
assertEquals(mt, t.getmetatable());
assertEquals("abc", t.get("ppp").tojstring());
assertEquals("def", t.get(123).tojstring());
assertEquals("ghi", t.get("qqq").tojstring());
assertEquals("jkl", t.get(456).tojstring());
assertEquals("nil", fb.get("ppp").tojstring());
assertEquals("nil", fb.get(123).tojstring());
assertEquals("ghi", fb.get("qqq").tojstring());
assertEquals("jkl", fb.get(456).tojstring());
assertEquals("nil", mt.get("ppp").tojstring());
assertEquals("nil", mt.get(123).tojstring());
assertEquals("nil", mt.get("qqq").tojstring());
assertEquals("nil", mt.get(456).tojstring());
// set metatable to metatable without values
t.setmetatable(fb);
assertEquals( "abc", t.get("ppp").tojstring() );
assertEquals( "def", t.get(123).tojstring() );
assertEquals( "nil", t.get("qqq").tojstring() );
assertEquals( "nil", t.get(456).tojstring() );
assertEquals("abc", t.get("ppp").tojstring());
assertEquals("def", t.get(123).tojstring());
assertEquals("nil", t.get("qqq").tojstring());
assertEquals("nil", t.get(456).tojstring());
// set metatable to null
t.setmetatable(null);
assertEquals( "abc", t.get("ppp").tojstring() );
assertEquals( "def", t.get(123).tojstring() );
assertEquals( "nil", t.get("qqq").tojstring() );
assertEquals( "nil", t.get(456).tojstring() );
}
assertEquals("abc", t.get("ppp").tojstring());
assertEquals("def", t.get(123).tojstring());
assertEquals("nil", t.get("qqq").tojstring());
assertEquals("nil", t.get(456).tojstring());
}
public void testIndexFunction() {
final LuaTable t = new_Table();
final LuaTable mt = new_Table();
final LuaTable mt = new_Table();
final TwoArgFunction fb = new TwoArgFunction() {
public LuaValue call(LuaValue tbl, LuaValue key) {
assertEquals(tbl, t);
return valueOf("from mt: "+key);
return valueOf("from mt: " + key);
}
};
// set basic values
t.set( "ppp", "abc" );
t.set( 123, "def" );
t.set("ppp", "abc");
t.set(123, "def");
mt.set(LuaValue.INDEX, fb);
// check before setting metatable
assertEquals( "abc", t.get("ppp").tojstring() );
assertEquals( "def", t.get(123).tojstring() );
assertEquals( "nil", t.get("qqq").tojstring() );
assertEquals( "nil", t.get(456).tojstring() );
assertEquals("abc", t.get("ppp").tojstring());
assertEquals("def", t.get(123).tojstring());
assertEquals("nil", t.get("qqq").tojstring());
assertEquals("nil", t.get(456).tojstring());
// check before setting metatable
t.setmetatable(mt);
assertEquals( mt, t.getmetatable() );
assertEquals( "abc", t.get("ppp").tojstring() );
assertEquals( "def", t.get(123).tojstring() );
assertEquals( "from mt: qqq", t.get("qqq").tojstring() );
assertEquals( "from mt: 456", t.get(456).tojstring() );
assertEquals(mt, t.getmetatable());
assertEquals("abc", t.get("ppp").tojstring());
assertEquals("def", t.get(123).tojstring());
assertEquals("from mt: qqq", t.get("qqq").tojstring());
assertEquals("from mt: 456", t.get(456).tojstring());
// use raw set
t.rawset("qqq", "alt-qqq");
t.rawset(456, "alt-456");
assertEquals( "abc", t.get("ppp").tojstring() );
assertEquals( "def", t.get(123).tojstring() );
assertEquals( "alt-qqq", t.get("qqq").tojstring() );
assertEquals( "alt-456", t.get(456).tojstring() );
assertEquals("abc", t.get("ppp").tojstring());
assertEquals("def", t.get(123).tojstring());
assertEquals("alt-qqq", t.get("qqq").tojstring());
assertEquals("alt-456", t.get(456).tojstring());
// remove using raw set
t.rawset("qqq", LuaValue.NIL);
t.rawset(456, LuaValue.NIL);
assertEquals( "abc", t.get("ppp").tojstring() );
assertEquals( "def", t.get(123).tojstring() );
assertEquals( "from mt: qqq", t.get("qqq").tojstring() );
assertEquals( "from mt: 456", t.get(456).tojstring() );
assertEquals("abc", t.get("ppp").tojstring());
assertEquals("def", t.get(123).tojstring());
assertEquals("from mt: qqq", t.get("qqq").tojstring());
assertEquals("from mt: 456", t.get(456).tojstring());
// set metatable to null
t.setmetatable(null);
assertEquals( "abc", t.get("ppp").tojstring() );
assertEquals( "def", t.get(123).tojstring() );
assertEquals( "nil", t.get("qqq").tojstring() );
assertEquals( "nil", t.get(456).tojstring() );
assertEquals("abc", t.get("ppp").tojstring());
assertEquals("def", t.get(123).tojstring());
assertEquals("nil", t.get("qqq").tojstring());
assertEquals("nil", t.get(456).tojstring());
}
public void testNext() {
final LuaTable t = new_Table();
assertEquals( LuaValue.NIL, t.next(LuaValue.NIL) );
assertEquals(LuaValue.NIL, t.next(LuaValue.NIL));
// insert array elements
t.set( 1, "one" );
assertEquals( LuaValue.valueOf(1), t.next(LuaValue.NIL).arg(1) );
assertEquals( LuaValue.valueOf("one"), t.next(LuaValue.NIL).arg(2) );
assertEquals( LuaValue.NIL, t.next(LuaValue.ONE) );
t.set( 2, "two" );
assertEquals( LuaValue.valueOf(1), t.next(LuaValue.NIL).arg(1) );
assertEquals( LuaValue.valueOf("one"), t.next(LuaValue.NIL).arg(2) );
assertEquals( LuaValue.valueOf(2), t.next(LuaValue.ONE).arg(1) );
assertEquals( LuaValue.valueOf("two"), t.next(LuaValue.ONE).arg(2) );
assertEquals( LuaValue.NIL, t.next(LuaValue.valueOf(2)) );
t.set(1, "one");
assertEquals(LuaValue.valueOf(1), t.next(LuaValue.NIL).arg(1));
assertEquals(LuaValue.valueOf("one"), t.next(LuaValue.NIL).arg(2));
assertEquals(LuaValue.NIL, t.next(LuaValue.ONE));
t.set(2, "two");
assertEquals(LuaValue.valueOf(1), t.next(LuaValue.NIL).arg(1));
assertEquals(LuaValue.valueOf("one"), t.next(LuaValue.NIL).arg(2));
assertEquals(LuaValue.valueOf(2), t.next(LuaValue.ONE).arg(1));
assertEquals(LuaValue.valueOf("two"), t.next(LuaValue.ONE).arg(2));
assertEquals(LuaValue.NIL, t.next(LuaValue.valueOf(2)));
// insert hash elements
t.set( "aa", "aaa" );
assertEquals( LuaValue.valueOf(1), t.next(LuaValue.NIL).arg(1) );
assertEquals( LuaValue.valueOf("one"), t.next(LuaValue.NIL).arg(2) );
assertEquals( LuaValue.valueOf(2), t.next(LuaValue.ONE).arg(1) );
assertEquals( LuaValue.valueOf("two"), t.next(LuaValue.ONE).arg(2) );
assertEquals( LuaValue.valueOf("aa"), t.next(LuaValue.valueOf(2)).arg(1) );
assertEquals( LuaValue.valueOf("aaa"), t.next(LuaValue.valueOf(2)).arg(2) );
assertEquals( LuaValue.NIL, t.next(LuaValue.valueOf("aa")) );
t.set( "bb", "bbb" );
assertEquals( LuaValue.valueOf(1), t.next(LuaValue.NIL).arg(1) );
assertEquals( LuaValue.valueOf("one"), t.next(LuaValue.NIL).arg(2) );
assertEquals( LuaValue.valueOf(2), t.next(LuaValue.ONE).arg(1) );
assertEquals( LuaValue.valueOf("two"), t.next(LuaValue.ONE).arg(2) );
assertEquals( LuaValue.valueOf("aa"), t.next(LuaValue.valueOf(2)).arg(1) );
assertEquals( LuaValue.valueOf("aaa"), t.next(LuaValue.valueOf(2)).arg(2) );
assertEquals( LuaValue.valueOf("bb"), t.next(LuaValue.valueOf("aa")).arg(1) );
assertEquals( LuaValue.valueOf("bbb"), t.next(LuaValue.valueOf("aa")).arg(2) );
assertEquals( LuaValue.NIL, t.next(LuaValue.valueOf("bb")) );
t.set("aa", "aaa");
assertEquals(LuaValue.valueOf(1), t.next(LuaValue.NIL).arg(1));
assertEquals(LuaValue.valueOf("one"), t.next(LuaValue.NIL).arg(2));
assertEquals(LuaValue.valueOf(2), t.next(LuaValue.ONE).arg(1));
assertEquals(LuaValue.valueOf("two"), t.next(LuaValue.ONE).arg(2));
assertEquals(LuaValue.valueOf("aa"), t.next(LuaValue.valueOf(2)).arg(1));
assertEquals(LuaValue.valueOf("aaa"), t.next(LuaValue.valueOf(2)).arg(2));
assertEquals(LuaValue.NIL, t.next(LuaValue.valueOf("aa")));
t.set("bb", "bbb");
assertEquals(LuaValue.valueOf(1), t.next(LuaValue.NIL).arg(1));
assertEquals(LuaValue.valueOf("one"), t.next(LuaValue.NIL).arg(2));
assertEquals(LuaValue.valueOf(2), t.next(LuaValue.ONE).arg(1));
assertEquals(LuaValue.valueOf("two"), t.next(LuaValue.ONE).arg(2));
assertEquals(LuaValue.valueOf("aa"), t.next(LuaValue.valueOf(2)).arg(1));
assertEquals(LuaValue.valueOf("aaa"), t.next(LuaValue.valueOf(2)).arg(2));
assertEquals(LuaValue.valueOf("bb"), t.next(LuaValue.valueOf("aa")).arg(1));
assertEquals(LuaValue.valueOf("bbb"), t.next(LuaValue.valueOf("aa")).arg(2));
assertEquals(LuaValue.NIL, t.next(LuaValue.valueOf("bb")));
}
public void testLoopWithRemoval() {
final LuaTable t = new_Table();
t.set( LuaValue.valueOf(1), LuaValue.valueOf("1") );
t.set( LuaValue.valueOf(3), LuaValue.valueOf("3") );
t.set( LuaValue.valueOf(8), LuaValue.valueOf("4") );
t.set( LuaValue.valueOf(17), LuaValue.valueOf("5") );
t.set( LuaValue.valueOf(26), LuaValue.valueOf("6") );
t.set( LuaValue.valueOf(35), LuaValue.valueOf("7") );
t.set( LuaValue.valueOf(42), LuaValue.valueOf("8") );
t.set( LuaValue.valueOf(60), LuaValue.valueOf("10") );
t.set( LuaValue.valueOf(63), LuaValue.valueOf("11") );
t.set(LuaValue.valueOf(1), LuaValue.valueOf("1"));
t.set(LuaValue.valueOf(3), LuaValue.valueOf("3"));
t.set(LuaValue.valueOf(8), LuaValue.valueOf("4"));
t.set(LuaValue.valueOf(17), LuaValue.valueOf("5"));
t.set(LuaValue.valueOf(26), LuaValue.valueOf("6"));
t.set(LuaValue.valueOf(35), LuaValue.valueOf("7"));
t.set(LuaValue.valueOf(42), LuaValue.valueOf("8"));
t.set(LuaValue.valueOf(60), LuaValue.valueOf("10"));
t.set(LuaValue.valueOf(63), LuaValue.valueOf("11"));
Varargs entry = t.next(LuaValue.NIL);
while ( !entry.isnil(1) ) {
LuaValue k = entry.arg1();
LuaValue v = entry.arg(2);
if ( ( k.toint() & 1 ) == 0 ) {
t.set( k, LuaValue.NIL );
if ((k.toint() & 1) == 0) {
t.set(k, LuaValue.NIL);
}
entry = t.next(k);
}
@@ -271,35 +270,35 @@ public class TableHashTest extends TestCase {
while ( !entry.isnil(1) ) {
LuaValue k = entry.arg1();
// Only odd keys should remain
assertTrue( ( k.toint() & 1 ) == 1 );
assertTrue((k.toint() & 1) == 1);
numEntries++;
entry = t.next(k);
}
assertEquals( 5, numEntries );
assertEquals(5, numEntries);
}
public void testLoopWithRemovalAndSet() {
final LuaTable t = new_Table();
t.set( LuaValue.valueOf(1), LuaValue.valueOf("1") );
t.set( LuaValue.valueOf(3), LuaValue.valueOf("3") );
t.set( LuaValue.valueOf(8), LuaValue.valueOf("4") );
t.set( LuaValue.valueOf(17), LuaValue.valueOf("5") );
t.set( LuaValue.valueOf(26), LuaValue.valueOf("6") );
t.set( LuaValue.valueOf(35), LuaValue.valueOf("7") );
t.set( LuaValue.valueOf(42), LuaValue.valueOf("8") );
t.set( LuaValue.valueOf(60), LuaValue.valueOf("10") );
t.set( LuaValue.valueOf(63), LuaValue.valueOf("11") );
t.set(LuaValue.valueOf(1), LuaValue.valueOf("1"));
t.set(LuaValue.valueOf(3), LuaValue.valueOf("3"));
t.set(LuaValue.valueOf(8), LuaValue.valueOf("4"));
t.set(LuaValue.valueOf(17), LuaValue.valueOf("5"));
t.set(LuaValue.valueOf(26), LuaValue.valueOf("6"));
t.set(LuaValue.valueOf(35), LuaValue.valueOf("7"));
t.set(LuaValue.valueOf(42), LuaValue.valueOf("8"));
t.set(LuaValue.valueOf(60), LuaValue.valueOf("10"));
t.set(LuaValue.valueOf(63), LuaValue.valueOf("11"));
Varargs entry = t.next(LuaValue.NIL);
Varargs entry2 = entry;
while ( !entry.isnil(1) ) {
LuaValue k = entry.arg1();
LuaValue v = entry.arg(2);
if ( ( k.toint() & 1 ) == 0 ) {
t.set( k, LuaValue.NIL );
if ((k.toint() & 1) == 0) {
t.set(k, LuaValue.NIL);
} else {
t.set( k, v.tonumber() );
t.set(k, v.tonumber());
entry2 = t.next(entry2.arg1());
}
entry = t.next(k);
@@ -310,11 +309,11 @@ public class TableHashTest extends TestCase {
while ( !entry.isnil(1) ) {
LuaValue k = entry.arg1();
// Only odd keys should remain
assertTrue( ( k.toint() & 1 ) == 1 );
assertTrue( entry.arg(2).type() == LuaValue.TNUMBER );
assertTrue((k.toint() & 1) == 1);
assertTrue(entry.arg(2).type() == LuaValue.TNUMBER);
numEntries++;
entry = t.next(k);
}
assertEquals( 5, numEntries );
assertEquals(5, numEntries);
}
}

View File

@@ -27,55 +27,54 @@ import java.util.Vector;
import junit.framework.TestCase;
public class TableTest extends TestCase {
protected LuaTable new_Table() {
return new LuaTable();
}
protected LuaTable new_Table(int n,int m) {
return new LuaTable(n,m);
protected LuaTable new_Table(int n, int m) {
return new LuaTable(n, m);
}
private int keyCount(LuaTable t) {
return keys(t).length;
}
private LuaValue[] keys(LuaTable t) {
ArrayList<LuaValue> l = new ArrayList<LuaValue>();
LuaValue k = LuaValue.NIL;
while ( true ) {
Varargs n = t.next(k);
if ( (k = n.arg1()).isnil() )
if ((k = n.arg1()).isnil())
break;
l.add( k );
l.add(k);
}
return l.toArray(new LuaValue[t.length()]);
}
public void testInOrderIntegerKeyInsertion() {
LuaTable t = new_Table();
for ( int i = 1; i <= 32; ++i ) {
t.set( i, LuaValue.valueOf( "Test Value! "+i ) );
for (int i = 1; i <= 32; ++i) {
t.set(i, LuaValue.valueOf("Test Value! " + i));
}
// Ensure all keys are still there.
for ( int i = 1; i <= 32; ++i ) {
assertEquals( "Test Value! " + i, t.get( i ).tojstring() );
for (int i = 1; i <= 32; ++i) {
assertEquals("Test Value! " + i, t.get(i).tojstring());
}
// Ensure capacities make sense
assertEquals( 0, t.getHashLength() );
assertTrue( t.getArrayLength() >= 32 );
assertTrue( t.getArrayLength() <= 64 );
assertEquals(0, t.getHashLength());
assertTrue(t.getArrayLength() >= 32);
assertTrue(t.getArrayLength() <= 64);
}
public void testRekeyCount() {
LuaTable t = new_Table();
// NOTE: This order of insertion is important.
t.set(3, LuaInteger.valueOf(3));
t.set(1, LuaInteger.valueOf(1));
@@ -83,142 +82,142 @@ public class TableTest extends TestCase {
t.set(4, LuaInteger.valueOf(4));
t.set(6, LuaInteger.valueOf(6));
t.set(2, LuaInteger.valueOf(2));
for ( int i = 1; i < 6; ++i ) {
for (int i = 1; i < 6; ++i) {
assertEquals(LuaInteger.valueOf(i), t.get(i));
}
assertTrue( t.getArrayLength() >= 3 );
assertTrue( t.getArrayLength() <= 12 );
assertTrue( t.getHashLength() <= 3 );
assertTrue(t.getArrayLength() >= 3);
assertTrue(t.getArrayLength() <= 12);
assertTrue(t.getHashLength() <= 3);
}
public void testOutOfOrderIntegerKeyInsertion() {
LuaTable t = new_Table();
for ( int i = 32; i > 0; --i ) {
t.set( i, LuaValue.valueOf( "Test Value! "+i ) );
for (int i = 32; i > 0; --i) {
t.set(i, LuaValue.valueOf("Test Value! " + i));
}
// Ensure all keys are still there.
for ( int i = 1; i <= 32; ++i ) {
assertEquals( "Test Value! "+i, t.get( i ).tojstring() );
for (int i = 1; i <= 32; ++i) {
assertEquals("Test Value! " + i, t.get(i).tojstring());
}
// Ensure capacities make sense
assertEquals( 32, t.getArrayLength() );
assertEquals( 0, t.getHashLength() );
assertEquals(32, t.getArrayLength());
assertEquals(0, t.getHashLength());
}
public void testStringAndIntegerKeys() {
LuaTable t = new_Table();
for ( int i = 0; i < 10; ++i ) {
LuaString str = LuaValue.valueOf( String.valueOf( i ) );
t.set( i, str );
t.set( str, LuaInteger.valueOf( i ) );
for (int i = 0; i < 10; ++i) {
LuaString str = LuaValue.valueOf(String.valueOf(i));
t.set(i, str);
t.set(str, LuaInteger.valueOf(i));
}
assertTrue( t.getArrayLength() >= 8 ); // 1, 2, ..., 9
assertTrue( t.getArrayLength() <= 16 );
assertTrue( t.getHashLength() >= 11 ); // 0, "0", "1", ..., "9"
assertTrue( t.getHashLength() <= 33 );
assertTrue(t.getArrayLength() >= 8); // 1, 2, ..., 9
assertTrue(t.getArrayLength() <= 16);
assertTrue(t.getHashLength() >= 11); // 0, "0", "1", ..., "9"
assertTrue(t.getHashLength() <= 33);
LuaValue[] keys = keys(t);
int intKeys = 0;
int stringKeys = 0;
assertEquals( 20, keys.length );
for ( int i = 0; i < keys.length; ++i ) {
assertEquals(20, keys.length);
for (int i = 0; i < keys.length; ++i) {
LuaValue k = keys[i];
if ( k instanceof LuaInteger ) {
if (k instanceof LuaInteger) {
final int ik = k.toint();
assertTrue( ik >= 0 && ik < 10 );
final int mask = 1 << ik;
assertTrue( ( intKeys & mask ) == 0 );
assertTrue(ik >= 0 && ik < 10);
final int mask = 1<<ik;
assertTrue((intKeys & mask) == 0);
intKeys |= mask;
} else if ( k instanceof LuaString ) {
final int ik = Integer.parseInt( k.strvalue().tojstring() );
assertEquals( String.valueOf( ik ), k.strvalue().tojstring() );
assertTrue( ik >= 0 && ik < 10 );
final int mask = 1 << ik;
assertTrue( "Key \""+ik+"\" found more than once", ( stringKeys & mask ) == 0 );
} else if (k instanceof LuaString) {
final int ik = Integer.parseInt(k.strvalue().tojstring());
assertEquals(String.valueOf(ik), k.strvalue().tojstring());
assertTrue(ik >= 0 && ik < 10);
final int mask = 1<<ik;
assertTrue("Key \"" + ik + "\" found more than once", (stringKeys & mask) == 0);
stringKeys |= mask;
} else {
fail( "Unexpected type of key found" );
fail("Unexpected type of key found");
}
}
assertEquals( 0x03FF, intKeys );
assertEquals( 0x03FF, stringKeys );
assertEquals(0x03FF, intKeys);
assertEquals(0x03FF, stringKeys);
}
public void testBadInitialCapacity() {
LuaTable t = new_Table(0, 1);
t.set( "test", LuaValue.valueOf("foo") );
t.set( "explode", LuaValue.valueOf("explode") );
assertEquals( 2, keyCount(t) );
t.set("test", LuaValue.valueOf("foo"));
t.set("explode", LuaValue.valueOf("explode"));
assertEquals(2, keyCount(t));
}
public void testRemove0() {
LuaTable t = new_Table(2, 0);
t.set( 1, LuaValue.valueOf("foo") );
t.set( 2, LuaValue.valueOf("bah") );
t.set(1, LuaValue.valueOf("foo"));
t.set(2, LuaValue.valueOf("bah"));
assertNotSame(LuaValue.NIL, t.get(1));
assertNotSame(LuaValue.NIL, t.get(2));
assertEquals(LuaValue.NIL, t.get(3));
t.set( 1, LuaValue.NIL );
t.set( 2, LuaValue.NIL );
t.set( 3, LuaValue.NIL );
t.set(1, LuaValue.NIL);
t.set(2, LuaValue.NIL);
t.set(3, LuaValue.NIL);
assertEquals(LuaValue.NIL, t.get(1));
assertEquals(LuaValue.NIL, t.get(2));
assertEquals(LuaValue.NIL, t.get(3));
}
public void testRemove1() {
LuaTable t = new_Table(0, 1);
t.set( "test", LuaValue.valueOf("foo") );
t.set( "explode", LuaValue.NIL );
t.set( 42, LuaValue.NIL );
t.set( new_Table(), LuaValue.NIL );
t.set( "test", LuaValue.NIL );
assertEquals( 0, keyCount(t) );
t.set( 10, LuaInteger.valueOf( 5 ) );
t.set( 10, LuaValue.NIL );
assertEquals( 0, keyCount(t) );
t.set("test", LuaValue.valueOf("foo"));
t.set("explode", LuaValue.NIL);
t.set(42, LuaValue.NIL);
t.set(new_Table(), LuaValue.NIL);
t.set("test", LuaValue.NIL);
assertEquals(0, keyCount(t));
t.set(10, LuaInteger.valueOf(5));
t.set(10, LuaValue.NIL);
assertEquals(0, keyCount(t));
}
public void testRemove2() {
LuaTable t = new_Table(0, 1);
t.set( "test", LuaValue.valueOf("foo") );
t.set( "string", LuaInteger.valueOf( 10 ) );
assertEquals( 2, keyCount(t) );
t.set( "string", LuaValue.NIL );
t.set( "three", LuaValue.valueOf( 3.14 ) );
assertEquals( 2, keyCount(t) );
t.set( "test", LuaValue.NIL );
assertEquals( 1, keyCount(t) );
t.set( 10, LuaInteger.valueOf( 5 ) );
assertEquals( 2, keyCount(t) );
t.set( 10, LuaValue.NIL );
assertEquals( 1, keyCount(t) );
t.set( "three", LuaValue.NIL );
assertEquals( 0, keyCount(t) );
t.set("test", LuaValue.valueOf("foo"));
t.set("string", LuaInteger.valueOf(10));
assertEquals(2, keyCount(t));
t.set("string", LuaValue.NIL);
t.set("three", LuaValue.valueOf(3.14));
assertEquals(2, keyCount(t));
t.set("test", LuaValue.NIL);
assertEquals(1, keyCount(t));
t.set(10, LuaInteger.valueOf(5));
assertEquals(2, keyCount(t));
t.set(10, LuaValue.NIL);
assertEquals(1, keyCount(t));
t.set("three", LuaValue.NIL);
assertEquals(0, keyCount(t));
}
public void testShrinkNonPowerOfTwoArray() {
LuaTable t = new_Table(6, 2);
@@ -256,157 +255,151 @@ public class TableTest extends TestCase {
public void testInOrderLuaLength() {
LuaTable t = new_Table();
for ( int i = 1; i <= 32; ++i ) {
t.set( i, LuaValue.valueOf( "Test Value! "+i ) );
assertEquals( i, t.length() );
for (int i = 1; i <= 32; ++i) {
t.set(i, LuaValue.valueOf("Test Value! " + i));
assertEquals(i, t.length());
}
}
public void testOutOfOrderLuaLength() {
LuaTable t = new_Table();
for ( int j=8; j<32; j+=8 ) {
for ( int i = j; i > 0; --i ) {
t.set( i, LuaValue.valueOf( "Test Value! "+i ) );
for (int j = 8; j < 32; j += 8) {
for (int i = j; i > 0; --i) {
t.set(i, LuaValue.valueOf("Test Value! " + i));
}
assertEquals( j, t.length() );
assertEquals(j, t.length());
}
}
public void testStringKeysLuaLength() {
LuaTable t = new_Table();
for ( int i = 1; i <= 32; ++i ) {
t.set( "str-"+i, LuaValue.valueOf( "String Key Test Value! "+i ) );
assertEquals( 0, t.length() );
for (int i = 1; i <= 32; ++i) {
t.set("str-" + i, LuaValue.valueOf("String Key Test Value! " + i));
assertEquals(0, t.length());
}
}
public void testMixedKeysLuaLength() {
LuaTable t = new_Table();
for ( int i = 1; i <= 32; ++i ) {
t.set( "str-"+i, LuaValue.valueOf( "String Key Test Value! "+i ) );
t.set( i, LuaValue.valueOf( "Int Key Test Value! "+i ) );
assertEquals( i, t.length() );
for (int i = 1; i <= 32; ++i) {
t.set("str-" + i, LuaValue.valueOf("String Key Test Value! " + i));
t.set(i, LuaValue.valueOf("Int Key Test Value! " + i));
assertEquals(i, t.length());
}
}
private static final void compareLists(LuaTable t,Vector v) {
private static final void compareLists(LuaTable t, Vector v) {
int n = v.size();
assertEquals(v.size(),t.length());
for ( int j=0; j<n; j++ ) {
assertEquals(v.size(), t.length());
for (int j = 0; j < n; j++) {
Object vj = v.elementAt(j);
Object tj = t.get(j+1).tojstring();
vj = ((LuaString)vj).tojstring();
assertEquals(vj,tj);
vj = ((LuaString) vj).tojstring();
assertEquals(vj, tj);
}
}
public void testInsertBeginningOfList() {
LuaTable t = new_Table();
Vector v = new Vector();
for ( int i = 1; i <= 32; ++i ) {
LuaString test = LuaValue.valueOf("Test Value! "+i);
for (int i = 1; i <= 32; ++i) {
LuaString test = LuaValue.valueOf("Test Value! " + i);
t.insert(1, test);
v.insertElementAt(test, 0);
compareLists(t,v);
v.insertElementAt(test, 0);
compareLists(t, v);
}
}
public void testInsertEndOfList() {
LuaTable t = new_Table();
Vector v = new Vector();
for ( int i = 1; i <= 32; ++i ) {
LuaString test = LuaValue.valueOf("Test Value! "+i);
for (int i = 1; i <= 32; ++i) {
LuaString test = LuaValue.valueOf("Test Value! " + i);
t.insert(0, test);
v.insertElementAt(test, v.size());
compareLists(t,v);
v.insertElementAt(test, v.size());
compareLists(t, v);
}
}
public void testInsertMiddleOfList() {
LuaTable t = new_Table();
Vector v = new Vector();
for ( int i = 1; i <= 32; ++i ) {
LuaString test = LuaValue.valueOf("Test Value! "+i);
int m = i / 2;
for (int i = 1; i <= 32; ++i) {
LuaString test = LuaValue.valueOf("Test Value! " + i);
int m = i/2;
t.insert(m+1, test);
v.insertElementAt(test, m);
compareLists(t,v);
compareLists(t, v);
}
}
private static final void prefillLists(LuaTable t,Vector v) {
for ( int i = 1; i <= 32; ++i ) {
LuaString test = LuaValue.valueOf("Test Value! "+i);
private static final void prefillLists(LuaTable t, Vector v) {
for (int i = 1; i <= 32; ++i) {
LuaString test = LuaValue.valueOf("Test Value! " + i);
t.insert(0, test);
v.insertElementAt(test, v.size());
}
}
public void testRemoveBeginningOfList() {
LuaTable t = new_Table();
Vector v = new Vector();
prefillLists(t,v);
for ( int i = 1; i <= 32; ++i ) {
prefillLists(t, v);
for (int i = 1; i <= 32; ++i) {
t.remove(1);
v.removeElementAt(0);
compareLists(t,v);
compareLists(t, v);
}
}
public void testRemoveEndOfList() {
LuaTable t = new_Table();
Vector v = new Vector();
prefillLists(t,v);
for ( int i = 1; i <= 32; ++i ) {
prefillLists(t, v);
for (int i = 1; i <= 32; ++i) {
t.remove(0);
v.removeElementAt(v.size()-1);
compareLists(t,v);
compareLists(t, v);
}
}
public void testRemoveMiddleOfList() {
LuaTable t = new_Table();
Vector v = new Vector();
prefillLists(t,v);
for ( int i = 1; i <= 32; ++i ) {
int m = v.size() / 2;
prefillLists(t, v);
for (int i = 1; i <= 32; ++i) {
int m = v.size()/2;
t.remove(m+1);
v.removeElementAt(m);
compareLists(t,v);
compareLists(t, v);
}
}
public void testRemoveWhileIterating() {
LuaTable t = LuaValue.tableOf(new LuaValue[] {
LuaValue.valueOf("a"), LuaValue.valueOf("aa"),
LuaValue.valueOf("b"), LuaValue.valueOf("bb"),
LuaValue.valueOf("c"), LuaValue.valueOf("cc"),
LuaValue.valueOf("d"), LuaValue.valueOf("dd"),
LuaValue.valueOf("e"), LuaValue.valueOf("ee"),
}, new LuaValue[] {
LuaValue.valueOf("11"),
LuaValue.valueOf("22"),
LuaValue.valueOf("33"),
LuaValue.valueOf("44"),
LuaValue.valueOf("55"),
});
LuaTable t = LuaValue.tableOf(
new LuaValue[] { LuaValue.valueOf("a"), LuaValue.valueOf("aa"), LuaValue.valueOf("b"),
LuaValue.valueOf("bb"), LuaValue.valueOf("c"), LuaValue.valueOf("cc"), LuaValue.valueOf("d"),
LuaValue.valueOf("dd"), LuaValue.valueOf("e"), LuaValue.valueOf("ee"), },
new LuaValue[] { LuaValue.valueOf("11"), LuaValue.valueOf("22"), LuaValue.valueOf("33"),
LuaValue.valueOf("44"), LuaValue.valueOf("55"), });
// Find expected order after removal.
java.util.List<String> expected = new java.util.ArrayList<String>();
Varargs n;
int i;
for (n = t.next(LuaValue.NIL), i = 0; !n.arg1().isnil(); n = t.next(n.arg1()), ++i) {
if (i % 2 == 0)
if (i%2 == 0)
expected.add(n.arg1() + "=" + n.arg(2));
}
// Remove every other key while iterating over the table.
for (n = t.next(LuaValue.NIL), i = 0; !n.arg1().isnil(); n = t.next(n.arg1()), ++i) {
if (i % 2 != 0)
if (i%2 != 0)
t.set(n.arg1(), LuaValue.NIL);
}
// Iterate over remaining table, and form list of entries still in table.
@@ -415,5 +408,5 @@ public class TableTest extends TestCase {
actual.add(n.arg1() + "=" + n.arg(2));
}
assertEquals(expected, actual);
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -25,12 +25,10 @@ import junit.framework.TestCase;
import org.luaj.vm2.lib.jse.JsePlatform;
public class UTF8StreamTest extends TestCase {
public class UTF8StreamTest extends TestCase {
public void testUtf8CharsInStream() {
String script = "x = \"98\u00b0: today's temp!\"\n"
+ "print('x = ', x)\n"
+ "return x";
String script = "x = \"98\u00b0: today's temp!\"\n" + "print('x = ', x)\n" + "return x";
Globals globals = JsePlatform.standardGlobals();
LuaValue chunk = globals.load(script);
LuaValue result = chunk.call();

View File

@@ -28,34 +28,34 @@ import junit.framework.TestCase;
*/
public class VarargsTest extends TestCase {
static LuaValue A = LuaValue.valueOf("a");
static LuaValue B = LuaValue.valueOf("b");
static LuaValue C = LuaValue.valueOf("c");
static LuaValue D = LuaValue.valueOf("d");
static LuaValue E = LuaValue.valueOf("e");
static LuaValue F = LuaValue.valueOf("f");
static LuaValue G = LuaValue.valueOf("g");
static LuaValue H = LuaValue.valueOf("h");
static LuaValue Z = LuaValue.valueOf("z");
static LuaValue NIL = LuaValue.NIL;
static Varargs A_G = LuaValue.varargsOf(new LuaValue[] { A, B, C, D, E, F, G });
static Varargs B_E = LuaValue.varargsOf(new LuaValue[] { B, C, D, E });
static Varargs C_G = LuaValue.varargsOf(new LuaValue[] { C, D, E, F, G });
static Varargs C_E = LuaValue.varargsOf(new LuaValue[] { C, D, E });
static Varargs DE = LuaValue.varargsOf(new LuaValue[] { D, E });
static Varargs E_G = LuaValue.varargsOf(new LuaValue[] { E, F, G });
static Varargs FG = LuaValue.varargsOf(new LuaValue[] { F, G });
static LuaValue[] Z_H_array = {Z, A, B, C, D, E, F, G, H };
static Varargs A_G_alt = new Varargs.ArrayPartVarargs(Z_H_array, 1, 7);
static Varargs B_E_alt = new Varargs.ArrayPartVarargs(Z_H_array, 2, 4);
static Varargs C_G_alt = new Varargs.ArrayPartVarargs(Z_H_array, 3, 5);
static Varargs C_E_alt = new Varargs.ArrayPartVarargs(Z_H_array, 3, 3);
static Varargs C_E_alt2 = LuaValue.varargsOf(C, D, E);
static Varargs DE_alt = new Varargs.PairVarargs(D,E);
static Varargs DE_alt2 = LuaValue.varargsOf(D,E);
static Varargs E_G_alt = new Varargs.ArrayPartVarargs(Z_H_array, 5, 3);
static Varargs FG_alt = new Varargs.PairVarargs(F, G);
static Varargs NONE = LuaValue.NONE;
static LuaValue A = LuaValue.valueOf("a");
static LuaValue B = LuaValue.valueOf("b");
static LuaValue C = LuaValue.valueOf("c");
static LuaValue D = LuaValue.valueOf("d");
static LuaValue E = LuaValue.valueOf("e");
static LuaValue F = LuaValue.valueOf("f");
static LuaValue G = LuaValue.valueOf("g");
static LuaValue H = LuaValue.valueOf("h");
static LuaValue Z = LuaValue.valueOf("z");
static LuaValue NIL = LuaValue.NIL;
static Varargs A_G = LuaValue.varargsOf(new LuaValue[] { A, B, C, D, E, F, G });
static Varargs B_E = LuaValue.varargsOf(new LuaValue[] { B, C, D, E });
static Varargs C_G = LuaValue.varargsOf(new LuaValue[] { C, D, E, F, G });
static Varargs C_E = LuaValue.varargsOf(new LuaValue[] { C, D, E });
static Varargs DE = LuaValue.varargsOf(new LuaValue[] { D, E });
static Varargs E_G = LuaValue.varargsOf(new LuaValue[] { E, F, G });
static Varargs FG = LuaValue.varargsOf(new LuaValue[] { F, G });
static LuaValue[] Z_H_array = { Z, A, B, C, D, E, F, G, H };
static Varargs A_G_alt = new Varargs.ArrayPartVarargs(Z_H_array, 1, 7);
static Varargs B_E_alt = new Varargs.ArrayPartVarargs(Z_H_array, 2, 4);
static Varargs C_G_alt = new Varargs.ArrayPartVarargs(Z_H_array, 3, 5);
static Varargs C_E_alt = new Varargs.ArrayPartVarargs(Z_H_array, 3, 3);
static Varargs C_E_alt2 = LuaValue.varargsOf(C, D, E);
static Varargs DE_alt = new Varargs.PairVarargs(D, E);
static Varargs DE_alt2 = LuaValue.varargsOf(D, E);
static Varargs E_G_alt = new Varargs.ArrayPartVarargs(Z_H_array, 5, 3);
static Varargs FG_alt = new Varargs.PairVarargs(F, G);
static Varargs NONE = LuaValue.NONE;
static void expectEquals(Varargs x, Varargs y) {
assertEquals(x.narg(), y.narg());
@@ -63,11 +63,11 @@ public class VarargsTest extends TestCase {
assertEquals(x.arg(0), y.arg(0));
assertEquals(x.arg(-1), y.arg(-1));
assertEquals(x.arg(2), y.arg(2));
assertEquals(x.arg(3), y.arg(3));
for (int i = 4; i < x.narg() + 2; ++i)
assertEquals(x.arg(3), y.arg(3));
for (int i = 4; i < x.narg()+2; ++i)
assertEquals(x.arg(i), y.arg(i));
}
public void testSanity() {
expectEquals(A_G, A_G);
expectEquals(A_G_alt, A_G_alt);
@@ -155,9 +155,9 @@ public class VarargsTest extends TestCase {
static void standardTestsNone(Varargs none) {
expectEquals(NONE, none.subargs(1));
expectEquals(NONE, none.subargs(2));
expectEquals(NONE, none.subargs(2));
}
public void testVarargsSubargs() {
standardTestsA_G(A_G);
standardTestsA_G(A_G_alt);
@@ -169,35 +169,31 @@ public class VarargsTest extends TestCase {
standardTestsFG(FG_alt);
standardTestsNone(NONE);
}
public void testVarargsMore() {
Varargs a_g;
a_g = LuaValue.varargsOf(new LuaValue[] { A, }, LuaValue.varargsOf( new LuaValue[] { B, C, D, E, F, G }));
a_g = LuaValue.varargsOf(new LuaValue[] { A, }, LuaValue.varargsOf(new LuaValue[] { B, C, D, E, F, G }));
standardTestsA_G(a_g);
a_g = LuaValue.varargsOf(new LuaValue[] { A, B, }, LuaValue.varargsOf( new LuaValue[] { C, D, E, F, G }));
a_g = LuaValue.varargsOf(new LuaValue[] { A, B, }, LuaValue.varargsOf(new LuaValue[] { C, D, E, F, G }));
standardTestsA_G(a_g);
a_g = LuaValue.varargsOf(new LuaValue[] { A, B, C, }, LuaValue.varargsOf( new LuaValue[] { D, E, F, G }));
a_g = LuaValue.varargsOf(new LuaValue[] { A, B, C, }, LuaValue.varargsOf(new LuaValue[] { D, E, F, G }));
standardTestsA_G(a_g);
a_g = LuaValue.varargsOf(new LuaValue[] { A, B, C, D, }, LuaValue.varargsOf(E, F, G));
standardTestsA_G(a_g);
a_g = LuaValue.varargsOf(new LuaValue[] { A, B, C, D, E }, LuaValue.varargsOf( F, G ));
a_g = LuaValue.varargsOf(new LuaValue[] { A, B, C, D, E }, LuaValue.varargsOf(F, G));
standardTestsA_G(a_g);
a_g = LuaValue.varargsOf(new LuaValue[] { A, B, C, D, E, F, }, G );
a_g = LuaValue.varargsOf(new LuaValue[] { A, B, C, D, E, F, }, G);
standardTestsA_G(a_g);
}
public void testPairVarargsMore() {
Varargs a_g = new Varargs.PairVarargs(A,
new Varargs.PairVarargs(B,
new Varargs.PairVarargs(C,
new Varargs.PairVarargs(D,
new Varargs.PairVarargs(E,
new Varargs.PairVarargs(F, G))))));
Varargs a_g = new Varargs.PairVarargs(A, new Varargs.PairVarargs(B, new Varargs.PairVarargs(C,
new Varargs.PairVarargs(D, new Varargs.PairVarargs(E, new Varargs.PairVarargs(F, G))))));
standardTestsA_G(a_g);
}
public void testArrayPartMore() {
Varargs a_g;
Varargs a_g;
a_g = new Varargs.ArrayPartVarargs(Z_H_array, 1, 1, new Varargs.ArrayPartVarargs(Z_H_array, 2, 6));
standardTestsA_G(a_g);
a_g = new Varargs.ArrayPartVarargs(Z_H_array, 1, 2, new Varargs.ArrayPartVarargs(Z_H_array, 3, 5));
@@ -217,14 +213,14 @@ public class VarargsTest extends TestCase {
try {
v.subargs(0);
fail("Failed to throw exception for index 0");
} catch ( LuaError e ) {
} catch (LuaError e) {
assertEquals(expected_msg, e.getMessage());
}
try {
v.subargs(-1);
fail("Failed to throw exception for index -1");
} catch ( LuaError e ) {
} catch (LuaError e) {
assertEquals(expected_msg, e.getMessage());
}
}
}
}

View File

@@ -24,20 +24,24 @@ package org.luaj.vm2;
import java.lang.ref.WeakReference;
abstract public class WeakTableTest extends TableTest {
public static class MyData {
public final int value;
public MyData( int value ) {
public MyData(int value) {
this.value = value;
}
public int hashCode() {
return value;
}
public boolean equals( Object o ) {
return (o instanceof MyData) && ((MyData)o).value == value;
public boolean equals(Object o) {
return (o instanceof MyData) && ((MyData) o).value == value;
}
public String toString() {
return "mydata-"+value;
return "mydata-" + value;
}
}
@@ -48,24 +52,25 @@ abstract public class WeakTableTest extends TableTest {
Thread.sleep(20);
rt.gc();
Thread.sleep(20);
} catch ( Exception e ) {
} catch (Exception e) {
e.printStackTrace();
}
rt.gc();
}
public static class WeakValueTableTest extends WeakTableTest {
protected LuaTable new_Table() { return WeakTable.make(false, true); }
protected LuaTable new_Table(int n,int m) { return WeakTable.make(false, true); }
protected LuaTable new_Table(int n, int m) { return WeakTable.make(false, true); }
public void testWeakValuesTable() {
LuaTable t = new_Table();
Object obj = new Object();
LuaTable tableValue = new LuaTable();
LuaString stringValue = LuaString.valueOf("this is a test");
LuaTable tableValue2 = new LuaTable();
t.set("table", tableValue);
t.set("userdata", LuaValue.userdataOf(obj, null));
t.set("string", stringValue);
@@ -82,7 +87,7 @@ abstract public class WeakTableTest extends TableTest {
// nothing should be collected, since we have strong references here
collectGarbage();
// check that elements are still there
assertEquals(tableValue, t.get("table"));
assertEquals(stringValue, t.get("string"));
@@ -94,10 +99,10 @@ abstract public class WeakTableTest extends TableTest {
tableValue = null;
tableValue2 = null;
stringValue = null;
// Garbage collection should cause weak entries to be dropped.
collectGarbage();
// check that they are dropped
assertEquals(LuaValue.NIL, t.get("table"));
assertEquals(LuaValue.NIL, t.get("userdata"));
@@ -105,22 +110,23 @@ abstract public class WeakTableTest extends TableTest {
assertFalse("strings should not be in weak references", t.get("string").isnil());
}
}
public static class WeakKeyTableTest extends WeakTableTest {
protected LuaTable new_Table() { return WeakTable.make(true, false); }
protected LuaTable new_Table(int n,int m) { return WeakTable.make(true, false); }
protected LuaTable new_Table(int n, int m) { return WeakTable.make(true, false); }
public void testWeakKeysTable() {
LuaTable t = WeakTable.make(true, false);
LuaValue key = LuaValue.userdataOf(new MyData(111));
LuaValue val = LuaValue.userdataOf(new MyData(222));
// set up the table
t.set( key, val );
assertEquals( val, t.get(key) );
t.set(key, val);
assertEquals(val, t.get(key));
System.gc();
assertEquals( val, t.get(key) );
assertEquals(val, t.get(key));
// drop key and value references, replace them with new ones
WeakReference origkey = new WeakReference(key);
@@ -129,75 +135,75 @@ abstract public class WeakTableTest extends TableTest {
val = LuaValue.userdataOf(new MyData(222));
// new key and value should be interchangeable (feature of this test class)
assertEquals( key, origkey.get() );
assertEquals( val, origval.get() );
assertEquals( val, t.get(key) );
assertEquals( val, t.get((LuaValue) origkey.get()) );
assertEquals( origval.get(), t.get(key) );
assertEquals(key, origkey.get());
assertEquals(val, origval.get());
assertEquals(val, t.get(key));
assertEquals(val, t.get((LuaValue) origkey.get()));
assertEquals(origval.get(), t.get(key));
// value should not be reachable after gc
collectGarbage();
assertEquals( null, origkey.get() );
assertEquals( LuaValue.NIL, t.get(key) );
assertEquals(null, origkey.get());
assertEquals(LuaValue.NIL, t.get(key));
collectGarbage();
assertEquals( null, origval.get() );
assertEquals(null, origval.get());
}
public void testNext() {
LuaTable t = WeakTable.make(true, true);
LuaValue key = LuaValue.userdataOf(new MyData(111));
LuaValue val = LuaValue.userdataOf(new MyData(222));
LuaValue key2 = LuaValue.userdataOf(new MyData(333));
LuaValue val2 = LuaValue.userdataOf(new MyData(444));
LuaValue key3 = LuaValue.userdataOf(new MyData(555));
LuaValue val3 = LuaValue.userdataOf(new MyData(666));
// set up the table
t.set( key, val );
t.set( key2, val2 );
t.set( key3, val3 );
t.set(key, val);
t.set(key2, val2);
t.set(key3, val3);
// forget one of the keys
key2 = null;
val2 = null;
collectGarbage();
// table should have 2 entries
int size = 0;
for ( LuaValue k = t.next(LuaValue.NIL).arg1(); !k.isnil();
k = t.next(k).arg1() ) {
for (LuaValue k = t.next(LuaValue.NIL).arg1(); !k.isnil(); k = t.next(k).arg1()) {
size++;
}
assertEquals(2, size);
}
}
public static class WeakKeyValueTableTest extends WeakTableTest {
protected LuaTable new_Table() { return WeakTable.make(true, true); }
protected LuaTable new_Table(int n,int m) { return WeakTable.make(true, true); }
protected LuaTable new_Table(int n, int m) { return WeakTable.make(true, true); }
public void testWeakKeysValuesTable() {
LuaTable t = WeakTable.make(true, true);
LuaValue key = LuaValue.userdataOf(new MyData(111));
LuaValue val = LuaValue.userdataOf(new MyData(222));
LuaValue key2 = LuaValue.userdataOf(new MyData(333));
LuaValue val2 = LuaValue.userdataOf(new MyData(444));
LuaValue key3 = LuaValue.userdataOf(new MyData(555));
LuaValue val3 = LuaValue.userdataOf(new MyData(666));
// set up the table
t.set( key, val );
t.set( key2, val2 );
t.set( key3, val3 );
assertEquals( val, t.get(key) );
assertEquals( val2, t.get(key2) );
assertEquals( val3, t.get(key3) );
t.set(key, val);
t.set(key2, val2);
t.set(key3, val3);
assertEquals(val, t.get(key));
assertEquals(val2, t.get(key2));
assertEquals(val3, t.get(key3));
System.gc();
assertEquals( val, t.get(key) );
assertEquals( val2, t.get(key2) );
assertEquals( val3, t.get(key3) );
assertEquals(val, t.get(key));
assertEquals(val2, t.get(key2));
assertEquals(val3, t.get(key3));
// drop key and value references, replace them with new ones
WeakReference origkey = new WeakReference(key);
@@ -214,45 +220,43 @@ abstract public class WeakTableTest extends TableTest {
// no values should be reachable after gc
collectGarbage();
assertEquals( null, origkey.get() );
assertEquals( null, origval.get() );
assertEquals( null, origkey2.get() );
assertEquals( null, origval3.get() );
assertEquals( LuaValue.NIL, t.get(key) );
assertEquals( LuaValue.NIL, t.get(key2) );
assertEquals( LuaValue.NIL, t.get(key3) );
assertEquals(null, origkey.get());
assertEquals(null, origval.get());
assertEquals(null, origkey2.get());
assertEquals(null, origval3.get());
assertEquals(LuaValue.NIL, t.get(key));
assertEquals(LuaValue.NIL, t.get(key2));
assertEquals(LuaValue.NIL, t.get(key3));
// all originals should be gone after gc, then access
val2 = null;
key3 = null;
collectGarbage();
assertEquals( null, origval2.get() );
assertEquals( null, origkey3.get() );
assertEquals(null, origval2.get());
assertEquals(null, origkey3.get());
}
public void testReplace() {
LuaTable t = WeakTable.make(true, true);
LuaValue key = LuaValue.userdataOf(new MyData(111));
LuaValue val = LuaValue.userdataOf(new MyData(222));
LuaValue key2 = LuaValue.userdataOf(new MyData(333));
LuaValue val2 = LuaValue.userdataOf(new MyData(444));
LuaValue key3 = LuaValue.userdataOf(new MyData(555));
LuaValue val3 = LuaValue.userdataOf(new MyData(666));
// set up the table
t.set( key, val );
t.set( key2, val2 );
t.set( key3, val3 );
t.set(key, val);
t.set(key2, val2);
t.set(key3, val3);
LuaValue val4 = LuaValue.userdataOf(new MyData(777));
t.set( key2, val4 );
t.set(key2, val4);
// table should have 3 entries
int size = 0;
for ( LuaValue k = t.next(LuaValue.NIL).arg1();
!k.isnil() && size < 1000;
k = t.next(k).arg1() ) {
for (LuaValue k = t.next(LuaValue.NIL).arg1(); !k.isnil() && size < 1000; k = t.next(k).arg1()) {
size++;
}
assertEquals(3, size);

View File

@@ -19,105 +19,104 @@ import org.luaj.vm2.lib.jse.JsePlatform;
abstract public class AbstractUnitTests extends TestCase {
private final String dir;
private final String jar;
private Globals globals;
private final String dir;
private final String jar;
private Globals globals;
public AbstractUnitTests(String zipdir, String zipfile, String dir) {
URL zip = null;
public AbstractUnitTests(String zipdir, String zipfile, String dir) {
URL zip = null;
zip = getClass().getResource(zipfile);
if ( zip == null ) {
File file = new File(zipdir+"/"+zipfile);
if (zip == null) {
File file = new File(zipdir + "/" + zipfile);
try {
if ( file.exists() )
if (file.exists())
zip = file.toURI().toURL();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
if ( zip == null )
throw new RuntimeException("not found: "+zipfile);
this.jar = "jar:" + zip.toExternalForm()+ "!/";
this.dir = dir;
}
if (zip == null)
throw new RuntimeException("not found: " + zipfile);
this.jar = "jar:" + zip.toExternalForm() + "!/";
this.dir = dir;
}
protected void setUp() throws Exception {
super.setUp();
globals = JsePlatform.standardGlobals();
}
protected void setUp() throws Exception {
super.setUp();
globals = JsePlatform.standardGlobals();
}
protected String pathOfFile(String file) {
return jar + dir + "/" + file;
}
protected InputStream inputStreamOfPath(String path) throws IOException {
URL url = new URL(path);
return url.openStream();
}
protected InputStream inputStreamOfFile(String file) throws IOException {
return inputStreamOfPath(pathOfFile(file));
}
protected void doTest(String file) {
try {
// load source from jar
String path = pathOfFile(file);
byte[] lua = bytesFromJar(path);
protected String pathOfFile(String file) {
return jar + dir + "/" + file;
}
// compile in memory
InputStream is = new ByteArrayInputStream(lua);
Prototype p = globals.loadPrototype(is, "@" + file, "bt");
String actual = protoToString(p);
protected InputStream inputStreamOfPath(String path) throws IOException {
URL url = new URL(path);
return url.openStream();
}
// load expected value from jar
byte[] luac = bytesFromJar(path.substring(0, path.length()-4)+".lc");
Prototype e = loadFromBytes(luac, file);
String expected = protoToString(e);
protected InputStream inputStreamOfFile(String file) throws IOException {
return inputStreamOfPath(pathOfFile(file));
}
// compare results
assertEquals(expected, actual);
protected void doTest(String file) {
try {
// load source from jar
String path = pathOfFile(file);
byte[] lua = bytesFromJar(path);
// dump into memory
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DumpState.dump(p, baos, false);
byte[] dumped = baos.toByteArray();
// compile in memory
InputStream is = new ByteArrayInputStream(lua);
Prototype p = globals.loadPrototype(is, "@" + file, "bt");
String actual = protoToString(p);
// re-undump
Prototype p2 = loadFromBytes(dumped, file);
String actual2 = protoToString(p2);
// load expected value from jar
byte[] luac = bytesFromJar(path.substring(0, path.length()-4) + ".lc");
Prototype e = loadFromBytes(luac, file);
String expected = protoToString(e);
// compare again
assertEquals(actual, actual2);
// compare results
assertEquals(expected, actual);
} catch (IOException e) {
fail(e.toString());
}
}
// dump into memory
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DumpState.dump(p, baos, false);
byte[] dumped = baos.toByteArray();
protected byte[] bytesFromJar(String path) throws IOException {
InputStream is = inputStreamOfPath(path);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[2048];
int n;
while ((n = is.read(buffer)) >= 0)
baos.write(buffer, 0, n);
is.close();
return baos.toByteArray();
}
// re-undump
Prototype p2 = loadFromBytes(dumped, file);
String actual2 = protoToString(p2);
protected Prototype loadFromBytes(byte[] bytes, String script)
throws IOException {
InputStream is = new ByteArrayInputStream(bytes);
return globals.loadPrototype(is, script, "b");
}
// compare again
assertEquals(actual, actual2);
protected String protoToString(Prototype p) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
Print.ps = ps;
new Print().printFunction(p, true);
return baos.toString();
}
} catch (IOException e) {
fail(e.toString());
}
}
protected byte[] bytesFromJar(String path) throws IOException {
InputStream is = inputStreamOfPath(path);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[2048];
int n;
while ( (n = is.read(buffer)) >= 0 )
baos.write(buffer, 0, n);
is.close();
return baos.toByteArray();
}
protected Prototype loadFromBytes(byte[] bytes, String script) throws IOException {
InputStream is = new ByteArrayInputStream(bytes);
return globals.loadPrototype(is, script, "b");
}
protected String protoToString(Prototype p) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
Print.ps = ps;
new Print().printFunction(p, true);
return baos.toString();
}
}

View File

@@ -1,38 +1,62 @@
package org.luaj.vm2.compiler;
public class CompilerUnitTests extends AbstractUnitTests {
public CompilerUnitTests() {
super("test/lua", "luaj3.0-tests.zip", "lua5.2.1-tests");
}
public CompilerUnitTests() {
super("test/lua", "luaj3.0-tests.zip", "lua5.2.1-tests");
}
public void testAll() { doTest("all.lua"); }
public void testApi() { doTest("api.lua"); }
public void testAttrib() { doTest("attrib.lua"); }
public void testBig() { doTest("big.lua"); }
public void testBitwise() { doTest("bitwise.lua"); }
public void testCalls() { doTest("calls.lua"); }
public void testAll() { doTest("all.lua"); }
public void testApi() { doTest("api.lua"); }
public void testAttrib() { doTest("attrib.lua"); }
public void testBig() { doTest("big.lua"); }
public void testBitwise() { doTest("bitwise.lua"); }
public void testCalls() { doTest("calls.lua"); }
public void testChecktable() { doTest("checktable.lua"); }
public void testClosure() { doTest("closure.lua"); }
public void testCode() { doTest("code.lua"); }
public void testConstruct() { doTest("constructs.lua"); }
public void testCoroutine() { doTest("coroutine.lua"); }
public void testDb() { doTest("db.lua"); }
public void testErrors() { doTest("errors.lua"); }
public void testEvents() { doTest("events.lua"); }
public void testFiles() { doTest("files.lua"); }
public void testGc() { doTest("gc.lua"); }
public void testGoto() { doTest("goto.lua"); }
public void testLiterals() { doTest("literals.lua"); }
public void testLocals() { doTest("locals.lua"); }
public void testMain() { doTest("main.lua"); }
public void testMath() { doTest("math.lua"); }
public void testNextvar() { doTest("nextvar.lua"); }
public void testPm() { doTest("pm.lua"); }
public void testSort() { doTest("sort.lua"); }
public void testStrings() { doTest("strings.lua"); }
public void testVararg() { doTest("vararg.lua"); }
public void testVerybig() { doTest("verybig.lua"); }
public void testClosure() { doTest("closure.lua"); }
public void testCode() { doTest("code.lua"); }
public void testConstruct() { doTest("constructs.lua"); }
public void testCoroutine() { doTest("coroutine.lua"); }
public void testDb() { doTest("db.lua"); }
public void testErrors() { doTest("errors.lua"); }
public void testEvents() { doTest("events.lua"); }
public void testFiles() { doTest("files.lua"); }
public void testGc() { doTest("gc.lua"); }
public void testGoto() { doTest("goto.lua"); }
public void testLiterals() { doTest("literals.lua"); }
public void testLocals() { doTest("locals.lua"); }
public void testMain() { doTest("main.lua"); }
public void testMath() { doTest("math.lua"); }
public void testNextvar() { doTest("nextvar.lua"); }
public void testPm() { doTest("pm.lua"); }
public void testSort() { doTest("sort.lua"); }
public void testStrings() { doTest("strings.lua"); }
public void testVararg() { doTest("vararg.lua"); }
public void testVerybig() { doTest("verybig.lua"); }
}

View File

@@ -19,119 +19,121 @@ import org.luaj.vm2.LuaValue;
import org.luaj.vm2.Prototype;
import org.luaj.vm2.lib.jse.JsePlatform;
public class DumpLoadEndianIntTest extends TestCase {
private static final String SAVECHUNKS = "SAVECHUNKS";
private static final boolean SHOULDPASS = true;
private static final boolean SHOULDFAIL = false;
private static final String mixedscript = "return tostring(1234)..'-#!-'..tostring(23.75)";
private static final String intscript = "return tostring(1234)..'-#!-'..tostring(23)";
private static final String withdoubles = "1234-#!-23.75";
private static final String withints = "1234-#!-23";
private static final boolean SHOULDPASS = true;
private static final boolean SHOULDFAIL = false;
private static final String mixedscript = "return tostring(1234)..'-#!-'..tostring(23.75)";
private static final String intscript = "return tostring(1234)..'-#!-'..tostring(23)";
private static final String withdoubles = "1234-#!-23.75";
private static final String withints = "1234-#!-23";
private Globals globals;
private Globals globals;
protected void setUp() throws Exception {
super.setUp();
globals = JsePlatform.standardGlobals();
DumpState.ALLOW_INTEGER_CASTING = false;
}
protected void setUp() throws Exception {
super.setUp();
globals = JsePlatform.standardGlobals();
DumpState.ALLOW_INTEGER_CASTING = false;
}
public void testBigDoubleCompile() {
doTest( false, DumpState.NUMBER_FORMAT_FLOATS_OR_DOUBLES, false, mixedscript, withdoubles, withdoubles, SHOULDPASS );
doTest( false, DumpState.NUMBER_FORMAT_FLOATS_OR_DOUBLES, true, mixedscript, withdoubles, withdoubles, SHOULDPASS );
doTest(false, DumpState.NUMBER_FORMAT_FLOATS_OR_DOUBLES, false, mixedscript, withdoubles, withdoubles,
SHOULDPASS);
doTest(false, DumpState.NUMBER_FORMAT_FLOATS_OR_DOUBLES, true, mixedscript, withdoubles, withdoubles,
SHOULDPASS);
}
public void testLittleDoubleCompile() {
doTest( true, DumpState.NUMBER_FORMAT_FLOATS_OR_DOUBLES, false, mixedscript, withdoubles, withdoubles, SHOULDPASS );
doTest( true, DumpState.NUMBER_FORMAT_FLOATS_OR_DOUBLES, true, mixedscript, withdoubles, withdoubles, SHOULDPASS );
}
public void testBigIntCompile() {
DumpState.ALLOW_INTEGER_CASTING = true;
doTest( false, DumpState.NUMBER_FORMAT_INTS_ONLY, false, mixedscript, withdoubles, withints, SHOULDPASS );
doTest( false, DumpState.NUMBER_FORMAT_INTS_ONLY, true, mixedscript, withdoubles, withints, SHOULDPASS );
DumpState.ALLOW_INTEGER_CASTING = false;
doTest( false, DumpState.NUMBER_FORMAT_INTS_ONLY, false, mixedscript, withdoubles, withints, SHOULDFAIL );
doTest( false, DumpState.NUMBER_FORMAT_INTS_ONLY, true, mixedscript, withdoubles, withints, SHOULDFAIL );
doTest( false, DumpState.NUMBER_FORMAT_INTS_ONLY, false, intscript, withints, withints, SHOULDPASS );
doTest( false, DumpState.NUMBER_FORMAT_INTS_ONLY, true, intscript, withints, withints, SHOULDPASS );
}
public void testLittleIntCompile() {
DumpState.ALLOW_INTEGER_CASTING = true;
doTest( true, DumpState.NUMBER_FORMAT_INTS_ONLY, false, mixedscript, withdoubles, withints, SHOULDPASS );
doTest( true, DumpState.NUMBER_FORMAT_INTS_ONLY, true, mixedscript, withdoubles, withints, SHOULDPASS );
DumpState.ALLOW_INTEGER_CASTING = false;
doTest( true, DumpState.NUMBER_FORMAT_INTS_ONLY, false, mixedscript, withdoubles, withints, SHOULDFAIL );
doTest( true, DumpState.NUMBER_FORMAT_INTS_ONLY, true, mixedscript, withdoubles, withints, SHOULDFAIL );
doTest( true, DumpState.NUMBER_FORMAT_INTS_ONLY, false, intscript, withints, withints, SHOULDPASS );
doTest( true, DumpState.NUMBER_FORMAT_INTS_ONLY, true, intscript, withints, withints, SHOULDPASS );
}
public void testBigNumpatchCompile() {
doTest( false, DumpState.NUMBER_FORMAT_NUM_PATCH_INT32, false, mixedscript, withdoubles, withdoubles, SHOULDPASS );
doTest( false, DumpState.NUMBER_FORMAT_NUM_PATCH_INT32, true, mixedscript, withdoubles, withdoubles, SHOULDPASS );
}
public void testLittleNumpatchCompile() {
doTest( true, DumpState.NUMBER_FORMAT_NUM_PATCH_INT32, false, mixedscript, withdoubles, withdoubles, SHOULDPASS );
doTest( true, DumpState.NUMBER_FORMAT_NUM_PATCH_INT32, true, mixedscript, withdoubles, withdoubles, SHOULDPASS );
}
public void doTest( boolean littleEndian, int numberFormat, boolean stripDebug,
String script, String expectedPriorDump, String expectedPostDump, boolean shouldPass ) {
try {
// compile into prototype
Reader reader = new StringReader(script);
Prototype p = globals.compilePrototype(reader, "script");
// double check script result before dumping
LuaFunction f = new LuaClosure(p, globals);
LuaValue r = f.call();
String actual = r.tojstring();
assertEquals( expectedPriorDump, actual );
// dump into bytes
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
DumpState.dump(p, baos, stripDebug, numberFormat, littleEndian);
if ( ! shouldPass )
fail( "dump should not have succeeded" );
} catch ( Exception e ) {
if ( shouldPass )
fail( "dump threw "+e );
else
return;
}
byte[] dumped = baos.toByteArray();
// load again using compiler
InputStream is = new ByteArrayInputStream(dumped);
f = globals.load(is, "dumped", "b", globals).checkfunction();
r = f.call();
actual = r.tojstring();
assertEquals( expectedPostDump, actual );
// write test chunk
if ( System.getProperty(SAVECHUNKS) != null && script.equals(mixedscript) ) {
new File("build").mkdirs();
String filename = "build/test-"
+(littleEndian? "little-": "big-")
+(numberFormat==DumpState.NUMBER_FORMAT_FLOATS_OR_DOUBLES? "double-":
numberFormat==DumpState.NUMBER_FORMAT_INTS_ONLY? "int-":
numberFormat==DumpState.NUMBER_FORMAT_NUM_PATCH_INT32? "numpatch4-": "???-")
+(stripDebug? "nodebug-": "debug-")
+"bin.lua";
FileOutputStream fos = new FileOutputStream(filename);
fos.write( dumped );
fos.close();
}
} catch (IOException e) {
fail(e.toString());
}
public void testLittleDoubleCompile() {
doTest(true, DumpState.NUMBER_FORMAT_FLOATS_OR_DOUBLES, false, mixedscript, withdoubles, withdoubles,
SHOULDPASS);
doTest(true, DumpState.NUMBER_FORMAT_FLOATS_OR_DOUBLES, true, mixedscript, withdoubles, withdoubles,
SHOULDPASS);
}
public void testBigIntCompile() {
DumpState.ALLOW_INTEGER_CASTING = true;
doTest(false, DumpState.NUMBER_FORMAT_INTS_ONLY, false, mixedscript, withdoubles, withints, SHOULDPASS);
doTest(false, DumpState.NUMBER_FORMAT_INTS_ONLY, true, mixedscript, withdoubles, withints, SHOULDPASS);
DumpState.ALLOW_INTEGER_CASTING = false;
doTest(false, DumpState.NUMBER_FORMAT_INTS_ONLY, false, mixedscript, withdoubles, withints, SHOULDFAIL);
doTest(false, DumpState.NUMBER_FORMAT_INTS_ONLY, true, mixedscript, withdoubles, withints, SHOULDFAIL);
doTest(false, DumpState.NUMBER_FORMAT_INTS_ONLY, false, intscript, withints, withints, SHOULDPASS);
doTest(false, DumpState.NUMBER_FORMAT_INTS_ONLY, true, intscript, withints, withints, SHOULDPASS);
}
public void testLittleIntCompile() {
DumpState.ALLOW_INTEGER_CASTING = true;
doTest(true, DumpState.NUMBER_FORMAT_INTS_ONLY, false, mixedscript, withdoubles, withints, SHOULDPASS);
doTest(true, DumpState.NUMBER_FORMAT_INTS_ONLY, true, mixedscript, withdoubles, withints, SHOULDPASS);
DumpState.ALLOW_INTEGER_CASTING = false;
doTest(true, DumpState.NUMBER_FORMAT_INTS_ONLY, false, mixedscript, withdoubles, withints, SHOULDFAIL);
doTest(true, DumpState.NUMBER_FORMAT_INTS_ONLY, true, mixedscript, withdoubles, withints, SHOULDFAIL);
doTest(true, DumpState.NUMBER_FORMAT_INTS_ONLY, false, intscript, withints, withints, SHOULDPASS);
doTest(true, DumpState.NUMBER_FORMAT_INTS_ONLY, true, intscript, withints, withints, SHOULDPASS);
}
public void testBigNumpatchCompile() {
doTest(false, DumpState.NUMBER_FORMAT_NUM_PATCH_INT32, false, mixedscript, withdoubles, withdoubles,
SHOULDPASS);
doTest(false, DumpState.NUMBER_FORMAT_NUM_PATCH_INT32, true, mixedscript, withdoubles, withdoubles, SHOULDPASS);
}
public void testLittleNumpatchCompile() {
doTest(true, DumpState.NUMBER_FORMAT_NUM_PATCH_INT32, false, mixedscript, withdoubles, withdoubles, SHOULDPASS);
doTest(true, DumpState.NUMBER_FORMAT_NUM_PATCH_INT32, true, mixedscript, withdoubles, withdoubles, SHOULDPASS);
}
public void doTest(boolean littleEndian, int numberFormat, boolean stripDebug, String script,
String expectedPriorDump, String expectedPostDump, boolean shouldPass) {
try {
// compile into prototype
Reader reader = new StringReader(script);
Prototype p = globals.compilePrototype(reader, "script");
// double check script result before dumping
LuaFunction f = new LuaClosure(p, globals);
LuaValue r = f.call();
String actual = r.tojstring();
assertEquals(expectedPriorDump, actual);
// dump into bytes
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
DumpState.dump(p, baos, stripDebug, numberFormat, littleEndian);
if (!shouldPass)
fail("dump should not have succeeded");
} catch (Exception e) {
if (shouldPass)
fail("dump threw " + e);
else
return;
}
byte[] dumped = baos.toByteArray();
// load again using compiler
InputStream is = new ByteArrayInputStream(dumped);
f = globals.load(is, "dumped", "b", globals).checkfunction();
r = f.call();
actual = r.tojstring();
assertEquals(expectedPostDump, actual);
// write test chunk
if (System.getProperty(SAVECHUNKS) != null && script.equals(mixedscript)) {
new File("build").mkdirs();
String filename = "build/test-" + (littleEndian? "little-": "big-")
+ (numberFormat == DumpState.NUMBER_FORMAT_FLOATS_OR_DOUBLES? "double-"
: numberFormat == DumpState.NUMBER_FORMAT_INTS_ONLY? "int-"
: numberFormat == DumpState.NUMBER_FORMAT_NUM_PATCH_INT32? "numpatch4-": "???-")
+ (stripDebug? "nodebug-": "debug-") + "bin.lua";
FileOutputStream fos = new FileOutputStream(filename);
fos.write(dumped);
fos.close();
}
} catch (IOException e) {
fail(e.toString());
}
}
}

View File

@@ -9,11 +9,11 @@ import org.luaj.vm2.parser.LuaParser;
public class LuaParserTests extends CompilerUnitTests {
protected void setUp() throws Exception {
super.setUp();
LuaValue.valueOf(true);
}
protected void setUp() throws Exception {
super.setUp();
LuaValue.valueOf(true);
}
protected void doTest(String file) {
try {
InputStream is = inputStreamOfFile(file);

View File

@@ -3,28 +3,32 @@ package org.luaj.vm2.compiler;
/**
* Framework to add regression tests as problem areas are found.
*
* To add a new regression test:
* 1) run "unpack.sh" in the project root
* 2) add a new "lua" file in the "regressions" subdirectory
* 3) run "repack.sh" in the project root
* 4) add a line to the source file naming the new test
* To add a new regression test: 1) run "unpack.sh" in the project root 2) add a
* new "lua" file in the "regressions" subdirectory 3) run "repack.sh" in the
* project root 4) add a line to the source file naming the new test
*
* After adding a test, check in the zip file
* rather than the individual regression test files.
* After adding a test, check in the zip file rather than the individual
* regression test files.
*
* @author jrosebor
*/
public class RegressionTests extends AbstractUnitTests {
public RegressionTests() {
super( "test/lua", "luaj3.0-tests.zip", "regressions" );
super("test/lua", "luaj3.0-tests.zip", "regressions");
}
public void testModulo() { doTest("modulo.lua"); }
public void testConstruct() { doTest("construct.lua"); }
public void testBigAttrs() { doTest("bigattr.lua"); }
public void testControlChars() { doTest("controlchars.lua"); }
public void testComparators() { doTest("comparators.lua"); }
public void testMathRandomseed() { doTest("mathrandomseed.lua"); }
public void testVarargs() { doTest("varargs.lua"); }
public void testModulo() { doTest("modulo.lua"); }
public void testConstruct() { doTest("construct.lua"); }
public void testBigAttrs() { doTest("bigattr.lua"); }
public void testControlChars() { doTest("controlchars.lua"); }
public void testComparators() { doTest("comparators.lua"); }
public void testMathRandomseed() { doTest("mathrandomseed.lua"); }
public void testVarargs() { doTest("varargs.lua"); }
}

View File

@@ -12,85 +12,73 @@ public class SimpleTests extends TestCase {
private Globals globals;
protected void setUp() throws Exception {
super.setUp();
globals = JsePlatform.standardGlobals();
}
protected void setUp() throws Exception {
super.setUp();
globals = JsePlatform.standardGlobals();
}
private void doTest( String script ) {
try {
private void doTest(String script) {
try {
LuaValue c = globals.load(script, "script");
c.call();
} catch ( Exception e ) {
fail("i/o exception: "+e );
}
}
} catch (Exception e) {
fail("i/o exception: " + e);
}
}
public void testTrivial() {
public void testTrivial() {
String s = "print( 2 )\n";
doTest( s );
doTest(s);
}
public void testAlmostTrivial() {
String s = "print( 2 )\n" +
"print( 3 )\n";
doTest( s );
String s = "print( 2 )\n" + "print( 3 )\n";
doTest(s);
}
public void testSimple() {
String s = "print( 'hello, world' )\n"+
"for i = 2,4 do\n" +
" print( 'i', i )\n" +
"end\n";
doTest( s );
String s = "print( 'hello, world' )\n" + "for i = 2,4 do\n" + " print( 'i', i )\n" + "end\n";
doTest(s);
}
public void testBreak() {
String s = "a=1\n"+
"while true do\n"+
" if a>10 then\n"+
" break\n"+
" end\n"+
" a=a+1\n"+
" print( a )\n"+
"end\n";
doTest( s );
String s = "a=1\n" + "while true do\n" + " if a>10 then\n" + " break\n" + " end\n" + " a=a+1\n"
+ " print( a )\n" + "end\n";
doTest(s);
}
public void testShebang() {
String s = "#!../lua\n"+
"print( 2 )\n";
doTest( s );
String s = "#!../lua\n" + "print( 2 )\n";
doTest(s);
}
public void testInlineTable() {
String s = "A = {g=10}\n"+
"print( A )\n";
doTest( s );
String s = "A = {g=10}\n" + "print( A )\n";
doTest(s);
}
public void testEqualsAnd() {
String s = "print( 1 == b and b )\n";
doTest( s );
doTest(s);
}
private static final int [] samehash = { 0, 1, -1, 2, -2, 4, 8, 16, 32, Integer.MAX_VALUE, Integer.MIN_VALUE };
private static final double [] diffhash = { .5, 1, 1.5, 1, .5, 1.5, 1.25, 2.5 };
private static final int[] samehash = { 0, 1, -1, 2, -2, 4, 8, 16, 32, Integer.MAX_VALUE, Integer.MIN_VALUE };
private static final double[] diffhash = { .5, 1, 1.5, 1, .5, 1.5, 1.25, 2.5 };
public void testDoubleHashCode() {
for ( int i=0; i<samehash.length; i++ ) {
for (int i = 0; i < samehash.length; i++) {
LuaValue j = LuaInteger.valueOf(samehash[i]);
LuaValue d = LuaDouble.valueOf(samehash[i]);
int hj = j.hashCode();
int hd = d.hashCode();
assertEquals(hj, hd);
}
for ( int i=0; i<diffhash.length; i+=2 ) {
for (int i = 0; i < diffhash.length; i += 2) {
LuaValue c = LuaValue.valueOf(diffhash[i+0]);
LuaValue d = LuaValue.valueOf(diffhash[i+1]);
int hc = c.hashCode();
int hd = d.hashCode();
assertTrue("hash codes are same: "+hc,hc!=hd);
assertTrue("hash codes are same: " + hc, hc != hd);
}
}
}

View File

@@ -6,10 +6,9 @@ import org.luaj.vm2.Globals;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.Varargs;
public class JsePlatformTest extends TestCase {
public void testLuaMainPassesArguments() {
Globals globals = JsePlatform.standardGlobals();
Globals globals = JsePlatform.standardGlobals();
LuaValue chunk = globals.load("return #arg, arg.n, arg[2], arg[1]");
Varargs results = JsePlatform.luaMain(chunk, new String[] { "aaa", "bbb" });
assertEquals(results.narg(), 4);

View File

@@ -12,47 +12,47 @@ import org.luaj.vm2.lib.MathLib;
public class LuaJavaCoercionTest extends TestCase {
private static LuaValue globals;
private static LuaValue ZERO = LuaValue.ZERO;
private static LuaValue ONE = LuaValue.ONE;
private static LuaValue TWO = LuaValue.valueOf(2);
private static LuaValue THREE = LuaValue.valueOf(3);
private static LuaValue globals;
private static LuaValue ZERO = LuaValue.ZERO;
private static LuaValue ONE = LuaValue.ONE;
private static LuaValue TWO = LuaValue.valueOf(2);
private static LuaValue THREE = LuaValue.valueOf(3);
private static LuaString LENGTH = LuaString.valueOf("length");
protected void setUp() throws Exception {
super.setUp();
globals = JsePlatform.standardGlobals();
}
public void testJavaIntToLuaInt() {
Integer i = Integer.valueOf(777);
LuaValue v = CoerceJavaToLua.coerce(i);
assertEquals( LuaInteger.class, v.getClass() );
assertEquals( 777, v.toint() );
assertEquals(LuaInteger.class, v.getClass());
assertEquals(777, v.toint());
}
public void testLuaIntToJavaInt() {
LuaInteger i = LuaInteger.valueOf(777);
Object o = CoerceLuaToJava.coerce(i, int.class);
assertEquals( Integer.class, o.getClass() );
assertEquals( 777, ((Number)o).intValue() );
assertEquals(Integer.class, o.getClass());
assertEquals(777, ((Number) o).intValue());
o = CoerceLuaToJava.coerce(i, Integer.class);
assertEquals( Integer.class, o.getClass() );
assertEquals( new Integer(777), o );
assertEquals(Integer.class, o.getClass());
assertEquals(new Integer(777), o);
}
public void testJavaStringToLuaString() {
String s = new String("777");
LuaValue v = CoerceJavaToLua.coerce(s);
assertEquals( LuaString.class, v.getClass() );
assertEquals( "777", v.toString() );
assertEquals(LuaString.class, v.getClass());
assertEquals("777", v.toString());
}
public void testLuaStringToJavaString() {
LuaString s = LuaValue.valueOf("777");
Object o = CoerceLuaToJava.coerce(s, String.class);
assertEquals( String.class, o.getClass() );
assertEquals( "777", o );
assertEquals(String.class, o.getClass());
assertEquals("777", o);
}
public void testJavaClassToLuaUserdata() {
@@ -76,76 +76,76 @@ public class LuaJavaCoercionTest extends TestCase {
static class ClassA {
}
static class ClassB {
static class ClassB {
}
public void testJavaIntArrayToLuaTable() {
int[] i = { 222, 333 };
LuaValue v = CoerceJavaToLua.coerce(i);
assertEquals( JavaArray.class, v.getClass() );
assertEquals( LuaInteger.valueOf(222), v.get(ONE) );
assertEquals( LuaInteger.valueOf(333), v.get(TWO) );
assertEquals( TWO, v.get(LENGTH));
assertEquals( LuaValue.NIL, v.get(THREE) );
assertEquals( LuaValue.NIL, v.get(ZERO) );
assertEquals(JavaArray.class, v.getClass());
assertEquals(LuaInteger.valueOf(222), v.get(ONE));
assertEquals(LuaInteger.valueOf(333), v.get(TWO));
assertEquals(TWO, v.get(LENGTH));
assertEquals(LuaValue.NIL, v.get(THREE));
assertEquals(LuaValue.NIL, v.get(ZERO));
v.set(ONE, LuaInteger.valueOf(444));
v.set(TWO, LuaInteger.valueOf(555));
assertEquals( 444, i[0] );
assertEquals( 555, i[1] );
assertEquals( LuaInteger.valueOf(444), v.get(ONE) );
assertEquals( LuaInteger.valueOf(555), v.get(TWO) );
assertEquals(444, i[0]);
assertEquals(555, i[1]);
assertEquals(LuaInteger.valueOf(444), v.get(ONE));
assertEquals(LuaInteger.valueOf(555), v.get(TWO));
try {
v.set(ZERO, LuaInteger.valueOf(777));
fail( "array bound exception not thrown" );
} catch ( LuaError lee ) {
fail("array bound exception not thrown");
} catch (LuaError lee) {
// expected
}
try {
v.set(THREE, LuaInteger.valueOf(777));
fail( "array bound exception not thrown" );
} catch ( LuaError lee ) {
fail("array bound exception not thrown");
} catch (LuaError lee) {
// expected
}
}
public void testLuaTableToJavaIntArray() {
LuaTable t = new LuaTable();
t.set(1, LuaInteger.valueOf(222) );
t.set(2, LuaInteger.valueOf(333) );
t.set(1, LuaInteger.valueOf(222));
t.set(2, LuaInteger.valueOf(333));
int[] i = null;
Object o = CoerceLuaToJava.coerce(t, int[].class);
assertEquals( int[].class, o.getClass() );
assertEquals(int[].class, o.getClass());
i = (int[]) o;
assertEquals( 2, i.length );
assertEquals( 222, i[0] );
assertEquals( 333, i[1] );
assertEquals(2, i.length);
assertEquals(222, i[0]);
assertEquals(333, i[1]);
}
public void testIntArrayScoringTables() {
int a = 5;
LuaValue la = LuaInteger.valueOf(a);
LuaTable tb = new LuaTable();
tb.set( 1, la );
tb.set(1, la);
LuaTable tc = new LuaTable();
tc.set( 1, tb );
tc.set(1, tb);
int saa = CoerceLuaToJava.getCoercion(int.class).score(la);
int sab = CoerceLuaToJava.getCoercion(int[].class).score(la);
int sac = CoerceLuaToJava.getCoercion(int[][].class).score(la);
assertTrue( saa < sab );
assertTrue( saa < sac );
assertTrue(saa < sab);
assertTrue(saa < sac);
int sba = CoerceLuaToJava.getCoercion(int.class).score(tb);
int sbb = CoerceLuaToJava.getCoercion(int[].class).score(tb);
int sbc = CoerceLuaToJava.getCoercion(int[][].class).score(tb);
assertTrue( sbb < sba );
assertTrue( sbb < sbc );
assertTrue(sbb < sba);
assertTrue(sbb < sbc);
int sca = CoerceLuaToJava.getCoercion(int.class).score(tc);
int scb = CoerceLuaToJava.getCoercion(int[].class).score(tc);
int scc = CoerceLuaToJava.getCoercion(int[][].class).score(tc);
assertTrue( scc < sca );
assertTrue( scc < scb );
assertTrue(scc < sca);
assertTrue(scc < scb);
}
public void testIntArrayScoringUserdata() {
int a = 5;
int[] b = { 44, 66 };
@@ -153,278 +153,325 @@ public class LuaJavaCoercionTest extends TestCase {
LuaValue va = CoerceJavaToLua.coerce(a);
LuaValue vb = CoerceJavaToLua.coerce(b);
LuaValue vc = CoerceJavaToLua.coerce(c);
int vaa = CoerceLuaToJava.getCoercion(int.class).score(va);
int vab = CoerceLuaToJava.getCoercion(int[].class).score(va);
int vac = CoerceLuaToJava.getCoercion(int[][].class).score(va);
assertTrue( vaa < vab );
assertTrue( vaa < vac );
assertTrue(vaa < vab);
assertTrue(vaa < vac);
int vba = CoerceLuaToJava.getCoercion(int.class).score(vb);
int vbb = CoerceLuaToJava.getCoercion(int[].class).score(vb);
int vbc = CoerceLuaToJava.getCoercion(int[][].class).score(vb);
assertTrue( vbb < vba );
assertTrue( vbb < vbc );
assertTrue(vbb < vba);
assertTrue(vbb < vbc);
int vca = CoerceLuaToJava.getCoercion(int.class).score(vc);
int vcb = CoerceLuaToJava.getCoercion(int[].class).score(vc);
int vcc = CoerceLuaToJava.getCoercion(int[][].class).score(vc);
assertTrue( vcc < vca );
assertTrue( vcc < vcb );
assertTrue(vcc < vca);
assertTrue(vcc < vcb);
}
public static class SampleClass {
public String sample() { return "void-args"; }
public String sample(int a) { return "int-args "+a; }
public String sample(int[] a) { return "int-array-args "+a[0]+","+a[1]; }
public String sample(int[][] a) { return "int-array-array-args "+a[0][0]+","+a[0][1]+","+a[1][0]+","+a[1][1]; }
public String sample(int a) { return "int-args " + a; }
public String sample(int[] a) { return "int-array-args " + a[0] + "," + a[1]; }
public String sample(int[][] a) {
return "int-array-array-args " + a[0][0] + "," + a[0][1] + "," + a[1][0] + "," + a[1][1];
}
}
public void testMatchVoidArgs() {
LuaValue v = CoerceJavaToLua.coerce(new SampleClass());
LuaValue result = v.method("sample");
assertEquals( "void-args", result.toString() );
assertEquals("void-args", result.toString());
}
public void testMatchIntArgs() {
LuaValue v = CoerceJavaToLua.coerce(new SampleClass());
LuaValue arg = CoerceJavaToLua.coerce(new Integer(123));
LuaValue result = v.method("sample",arg);
assertEquals( "int-args 123", result.toString() );
LuaValue result = v.method("sample", arg);
assertEquals("int-args 123", result.toString());
}
public void testMatchIntArrayArgs() {
LuaValue v = CoerceJavaToLua.coerce(new SampleClass());
LuaValue arg = CoerceJavaToLua.coerce(new int[]{345,678});
LuaValue result = v.method("sample",arg);
assertEquals( "int-array-args 345,678", result.toString() );
LuaValue arg = CoerceJavaToLua.coerce(new int[] { 345, 678 });
LuaValue result = v.method("sample", arg);
assertEquals("int-array-args 345,678", result.toString());
}
public void testMatchIntArrayArrayArgs() {
LuaValue v = CoerceJavaToLua.coerce(new SampleClass());
LuaValue arg = CoerceJavaToLua.coerce(new int[][]{{22,33},{44,55}});
LuaValue result = v.method("sample",arg);
assertEquals( "int-array-array-args 22,33,44,55", result.toString() );
LuaValue arg = CoerceJavaToLua.coerce(new int[][] { { 22, 33 }, { 44, 55 } });
LuaValue result = v.method("sample", arg);
assertEquals("int-array-array-args 22,33,44,55", result.toString());
}
public static final class SomeException extends RuntimeException {
public SomeException(String message) {
super(message);
}
}
public static final class SomeClass {
public static void someMethod() {
throw new SomeException( "this is some message" );
throw new SomeException("this is some message");
}
}
public void testExceptionMessage() {
String script = "local c = luajava.bindClass( \""+SomeClass.class.getName()+"\" )\n" +
"return pcall( c.someMethod, c )";
String script = "local c = luajava.bindClass( \"" + SomeClass.class.getName() + "\" )\n"
+ "return pcall( c.someMethod, c )";
Varargs vresult = globals.get("load").call(LuaValue.valueOf(script)).invoke(LuaValue.NONE);
LuaValue status = vresult.arg1();
LuaValue message = vresult.arg(2);
assertEquals( LuaValue.FALSE, status );
int index = message.toString().indexOf( "this is some message" );
assertTrue( "bad message: "+message, index>=0 );
assertEquals(LuaValue.FALSE, status);
int index = message.toString().indexOf("this is some message");
assertTrue("bad message: " + message, index >= 0);
}
public void testLuaErrorCause() {
String script = "luajava.bindClass( \""+SomeClass.class.getName()+"\"):someMethod()";
String script = "luajava.bindClass( \"" + SomeClass.class.getName() + "\"):someMethod()";
LuaValue chunk = globals.get("load").call(LuaValue.valueOf(script));
try {
chunk.invoke(LuaValue.NONE);
fail( "call should not have succeeded" );
} catch ( LuaError lee ) {
fail("call should not have succeeded");
} catch (LuaError lee) {
Throwable c = lee.getCause();
assertEquals( SomeException.class, c.getClass() );
assertEquals(SomeException.class, c.getClass());
}
}
public interface VarArgsInterface {
public String varargsMethod( String a, String ... v );
public String arrayargsMethod( String a, String[] v );
public String varargsMethod(String a, String... v);
public String arrayargsMethod(String a, String[] v);
}
public void testVarArgsProxy() {
String script = "return luajava.createProxy( \""+VarArgsInterface.class.getName()+"\", \n"+
"{\n" +
" varargsMethod = function(a,...)\n" +
" return table.concat({a,...},'-')\n" +
" end,\n" +
" arrayargsMethod = function(a,array)\n" +
" return tostring(a)..(array and \n" +
" ('-'..tostring(array.length)\n" +
" ..'-'..tostring(array[1])\n" +
" ..'-'..tostring(array[2])\n" +
" ) or '-nil')\n" +
" end,\n" +
"} )\n";
public void testVarArgsProxy() {
String script = "return luajava.createProxy( \"" + VarArgsInterface.class.getName() + "\", \n" + "{\n"
+ " varargsMethod = function(a,...)\n" + " return table.concat({a,...},'-')\n" + " end,\n"
+ " arrayargsMethod = function(a,array)\n" + " return tostring(a)..(array and \n"
+ " ('-'..tostring(array.length)\n" + " ..'-'..tostring(array[1])\n"
+ " ..'-'..tostring(array[2])\n" + " ) or '-nil')\n" + " end,\n" + "} )\n";
Varargs chunk = globals.get("load").call(LuaValue.valueOf(script));
if ( ! chunk.arg1().toboolean() )
fail( chunk.arg(2).toString() );
if (!chunk.arg1().toboolean())
fail(chunk.arg(2).toString());
LuaValue result = chunk.arg1().call();
Object u = result.touserdata();
VarArgsInterface v = (VarArgsInterface) u;
assertEquals( "foo", v.varargsMethod("foo") );
assertEquals( "foo-bar", v.varargsMethod("foo", "bar") );
assertEquals( "foo-bar-etc", v.varargsMethod("foo", "bar", "etc") );
assertEquals( "foo-0-nil-nil", v.arrayargsMethod("foo", new String[0]) );
assertEquals( "foo-1-bar-nil", v.arrayargsMethod("foo", new String[] {"bar"}) );
assertEquals( "foo-2-bar-etc", v.arrayargsMethod("foo", new String[] {"bar","etc"}) );
assertEquals( "foo-3-bar-etc", v.arrayargsMethod("foo", new String[] {"bar","etc","etc"}) );
assertEquals( "foo-nil", v.arrayargsMethod("foo", null) );
assertEquals("foo", v.varargsMethod("foo"));
assertEquals("foo-bar", v.varargsMethod("foo", "bar"));
assertEquals("foo-bar-etc", v.varargsMethod("foo", "bar", "etc"));
assertEquals("foo-0-nil-nil", v.arrayargsMethod("foo", new String[0]));
assertEquals("foo-1-bar-nil", v.arrayargsMethod("foo", new String[] { "bar" }));
assertEquals("foo-2-bar-etc", v.arrayargsMethod("foo", new String[] { "bar", "etc" }));
assertEquals("foo-3-bar-etc", v.arrayargsMethod("foo", new String[] { "bar", "etc", "etc" }));
assertEquals("foo-nil", v.arrayargsMethod("foo", null));
}
public void testBigNum() {
String script =
"bigNumA = luajava.newInstance('java.math.BigDecimal','12345678901234567890');\n" +
"bigNumB = luajava.newInstance('java.math.BigDecimal','12345678901234567890');\n" +
"bigNumC = bigNumA:multiply(bigNumB);\n" +
String script = "bigNumA = luajava.newInstance('java.math.BigDecimal','12345678901234567890');\n"
+ "bigNumB = luajava.newInstance('java.math.BigDecimal','12345678901234567890');\n"
+ "bigNumC = bigNumA:multiply(bigNumB);\n" +
//"print(bigNumA:toString())\n" +
//"print(bigNumB:toString())\n" +
//"print(bigNumC:toString())\n" +
"return bigNumA:toString(), bigNumB:toString(), bigNumC:toString()";
Varargs chunk = globals.get("load").call(LuaValue.valueOf(script));
if ( ! chunk.arg1().toboolean() )
fail( chunk.arg(2).toString() );
if (!chunk.arg1().toboolean())
fail(chunk.arg(2).toString());
Varargs results = chunk.arg1().invoke();
int nresults = results.narg();
String sa = results.tojstring(1);
String sb = results.tojstring(2);
String sc = results.tojstring(3);
assertEquals( 3, nresults );
assertEquals( "12345678901234567890", sa );
assertEquals( "12345678901234567890", sb );
assertEquals( "152415787532388367501905199875019052100", sc );
assertEquals(3, nresults);
assertEquals("12345678901234567890", sa);
assertEquals("12345678901234567890", sb);
assertEquals("152415787532388367501905199875019052100", sc);
}
public interface IA {}
public interface IB extends IA {}
public interface IC extends IB {}
public static class A implements IA {
public interface IA {
}
public interface IB extends IA {
}
public interface IC extends IB {
}
public static class A implements IA {
}
public static class B extends A implements IB {
public String set( Object x ) { return "set(Object) "; }
public String set( String x ) { return "set(String) "+x; }
public String set( A x ) { return "set(A) "; }
public String set( B x ) { return "set(B) "; }
public String set( C x ) { return "set(C) "; }
public String set( byte x ) { return "set(byte) "+x; }
public String set( char x ) { return "set(char) "+(int)x; }
public String set( short x ) { return "set(short) "+x; }
public String set( int x ) { return "set(int) "+x; }
public String set( long x ) { return "set(long) "+x; }
public String set( float x ) { return "set(float) "+x; }
public String set( double x ) { return "set(double) "+x; }
public String set(Object x) { return "set(Object) "; }
public String set(String x) { return "set(String) " + x; }
public String set(A x) { return "set(A) "; }
public String set(B x) { return "set(B) "; }
public String set(C x) { return "set(C) "; }
public String set(byte x) { return "set(byte) " + x; }
public String set(char x) { return "set(char) " + (int) x; }
public String set(short x) { return "set(short) " + x; }
public String set(int x) { return "set(int) " + x; }
public String set(long x) { return "set(long) " + x; }
public String set(float x) { return "set(float) " + x; }
public String set(double x) { return "set(double) " + x; }
public String setr(double x) { return "setr(double) " + x; }
public String setr(float x) { return "setr(float) " + x; }
public String setr(long x) { return "setr(long) " + x; }
public String setr(int x) { return "setr(int) " + x; }
public String setr(short x) { return "setr(short) " + x; }
public String setr(char x) { return "setr(char) " + (int) x; }
public String setr(byte x) { return "setr(byte) " + x; }
public String setr(C x) { return "setr(C) "; }
public String setr(B x) { return "setr(B) "; }
public String setr(A x) { return "setr(A) "; }
public String setr(String x) { return "setr(String) " + x; }
public String setr(Object x) { return "setr(Object) "; }
public String setr( double x ) { return "setr(double) "+x; }
public String setr( float x ) { return "setr(float) "+x; }
public String setr( long x ) { return "setr(long) "+x; }
public String setr( int x ) { return "setr(int) "+x; }
public String setr( short x ) { return "setr(short) "+x; }
public String setr( char x ) { return "setr(char) "+(int)x; }
public String setr( byte x ) { return "setr(byte) "+x; }
public String setr( C x ) { return "setr(C) "; }
public String setr( B x ) { return "setr(B) "; }
public String setr( A x ) { return "setr(A) "; }
public String setr( String x ) { return "setr(String) "+x; }
public String setr( Object x ) { return "setr(Object) "; }
public Object getObject() { return new Object(); }
public String getString() { return "abc"; }
public byte[] getbytearray() { return new byte[] { 1, 2, 3 }; }
public A getA() { return new A(); }
public B getB() { return new B(); }
public C getC() { return new C(); }
public byte getbyte() { return 1; }
public char getchar() { return 65000; }
public short getshort() { return -32000; }
public int getint() { return 100000; }
public long getlong() { return 50000000000L; }
public float getfloat() { return 6.5f; }
public double getdouble() { return Math.PI; }
}
public static class C extends B implements IC {
}
public static class D extends C implements IA {
}
public void testOverloadedJavaMethodObject() { doOverloadedMethodTest( "Object", "" ); }
public void testOverloadedJavaMethodString() { doOverloadedMethodTest( "String", "abc" ); }
public void testOverloadedJavaMethodA() { doOverloadedMethodTest( "A", "" ); }
public void testOverloadedJavaMethodB() { doOverloadedMethodTest( "B", "" ); }
public void testOverloadedJavaMethodC() { doOverloadedMethodTest( "C", "" ); }
public void testOverloadedJavaMethodByte() { doOverloadedMethodTest( "byte", "1" ); }
public void testOverloadedJavaMethodChar() { doOverloadedMethodTest( "char", "65000" ); }
public void testOverloadedJavaMethodShort() { doOverloadedMethodTest( "short", "-32000" ); }
public void testOverloadedJavaMethodInt() { doOverloadedMethodTest( "int", "100000" ); }
public void testOverloadedJavaMethodLong() { doOverloadedMethodTest( "long", "50000000000" ); }
public void testOverloadedJavaMethodFloat() { doOverloadedMethodTest( "float", "6.5" ); }
public void testOverloadedJavaMethodDouble() { doOverloadedMethodTest( "double", "3.141592653589793" ); }
private void doOverloadedMethodTest( String typename, String value ) {
String script =
"local a = luajava.newInstance('"+B.class.getName()+"');\n" +
"local b = a:set(a:get"+typename+"())\n" +
"local c = a:setr(a:get"+typename+"())\n" +
"return b,c";
public static class C extends B implements IC {
}
public static class D extends C implements IA {
}
public void testOverloadedJavaMethodObject() { doOverloadedMethodTest("Object", ""); }
public void testOverloadedJavaMethodString() { doOverloadedMethodTest("String", "abc"); }
public void testOverloadedJavaMethodA() { doOverloadedMethodTest("A", ""); }
public void testOverloadedJavaMethodB() { doOverloadedMethodTest("B", ""); }
public void testOverloadedJavaMethodC() { doOverloadedMethodTest("C", ""); }
public void testOverloadedJavaMethodByte() { doOverloadedMethodTest("byte", "1"); }
public void testOverloadedJavaMethodChar() { doOverloadedMethodTest("char", "65000"); }
public void testOverloadedJavaMethodShort() { doOverloadedMethodTest("short", "-32000"); }
public void testOverloadedJavaMethodInt() { doOverloadedMethodTest("int", "100000"); }
public void testOverloadedJavaMethodLong() { doOverloadedMethodTest("long", "50000000000"); }
public void testOverloadedJavaMethodFloat() { doOverloadedMethodTest("float", "6.5"); }
public void testOverloadedJavaMethodDouble() { doOverloadedMethodTest("double", "3.141592653589793"); }
private void doOverloadedMethodTest(String typename, String value) {
String script = "local a = luajava.newInstance('" + B.class.getName() + "');\n" + "local b = a:set(a:get"
+ typename + "())\n" + "local c = a:setr(a:get" + typename + "())\n" + "return b,c";
Varargs chunk = globals.get("load").call(LuaValue.valueOf(script));
if ( ! chunk.arg1().toboolean() )
fail( chunk.arg(2).toString() );
if (!chunk.arg1().toboolean())
fail(chunk.arg(2).toString());
Varargs results = chunk.arg1().invoke();
int nresults = results.narg();
assertEquals( 2, nresults );
assertEquals(2, nresults);
LuaValue b = results.arg(1);
LuaValue c = results.arg(2);
String sb = b.tojstring();
String sc = c.tojstring();
assertEquals( "set("+typename+") "+value, sb );
assertEquals( "setr("+typename+") "+value, sc );
assertEquals("set(" + typename + ") " + value, sb);
assertEquals("setr(" + typename + ") " + value, sc);
}
public void testClassInheritanceLevels() {
assertEquals( 0, CoerceLuaToJava.inheritanceLevels(Object.class, Object.class) );
assertEquals( 1, CoerceLuaToJava.inheritanceLevels(Object.class, String.class) );
assertEquals( 1, CoerceLuaToJava.inheritanceLevels(Object.class, A.class) );
assertEquals( 2, CoerceLuaToJava.inheritanceLevels(Object.class, B.class) );
assertEquals( 3, CoerceLuaToJava.inheritanceLevels(Object.class, C.class) );
assertEquals( CoerceLuaToJava.SCORE_UNCOERCIBLE, CoerceLuaToJava.inheritanceLevels(A.class, Object.class) );
assertEquals( CoerceLuaToJava.SCORE_UNCOERCIBLE, CoerceLuaToJava.inheritanceLevels(A.class, String.class) );
assertEquals( 0, CoerceLuaToJava.inheritanceLevels(A.class, A.class) );
assertEquals( 1, CoerceLuaToJava.inheritanceLevels(A.class, B.class) );
assertEquals( 2, CoerceLuaToJava.inheritanceLevels(A.class, C.class) );
assertEquals( CoerceLuaToJava.SCORE_UNCOERCIBLE, CoerceLuaToJava.inheritanceLevels(B.class, Object.class) );
assertEquals( CoerceLuaToJava.SCORE_UNCOERCIBLE, CoerceLuaToJava.inheritanceLevels(B.class, String.class) );
assertEquals( CoerceLuaToJava.SCORE_UNCOERCIBLE, CoerceLuaToJava.inheritanceLevels(B.class, A.class) );
assertEquals( 0, CoerceLuaToJava.inheritanceLevels(B.class, B.class) );
assertEquals( 1, CoerceLuaToJava.inheritanceLevels(B.class, C.class) );
assertEquals( CoerceLuaToJava.SCORE_UNCOERCIBLE, CoerceLuaToJava.inheritanceLevels(C.class, Object.class) );
assertEquals( CoerceLuaToJava.SCORE_UNCOERCIBLE, CoerceLuaToJava.inheritanceLevels(C.class, String.class) );
assertEquals( CoerceLuaToJava.SCORE_UNCOERCIBLE, CoerceLuaToJava.inheritanceLevels(C.class, A.class) );
assertEquals( CoerceLuaToJava.SCORE_UNCOERCIBLE, CoerceLuaToJava.inheritanceLevels(C.class, B.class) );
assertEquals( 0, CoerceLuaToJava.inheritanceLevels(C.class, C.class) );
}
public void testInterfaceInheritanceLevels() {
assertEquals( 1, CoerceLuaToJava.inheritanceLevels(IA.class, A.class) );
assertEquals( 1, CoerceLuaToJava.inheritanceLevels(IB.class, B.class) );
assertEquals( 2, CoerceLuaToJava.inheritanceLevels(IA.class, B.class) );
assertEquals( 1, CoerceLuaToJava.inheritanceLevels(IC.class, C.class) );
assertEquals( 2, CoerceLuaToJava.inheritanceLevels(IB.class, C.class) );
assertEquals( 3, CoerceLuaToJava.inheritanceLevels(IA.class, C.class) );
assertEquals( 1, CoerceLuaToJava.inheritanceLevels(IA.class, D.class) );
assertEquals( 2, CoerceLuaToJava.inheritanceLevels(IC.class, D.class) );
assertEquals( 3, CoerceLuaToJava.inheritanceLevels(IB.class, D.class) );
assertEquals(0, CoerceLuaToJava.inheritanceLevels(Object.class, Object.class));
assertEquals(1, CoerceLuaToJava.inheritanceLevels(Object.class, String.class));
assertEquals(1, CoerceLuaToJava.inheritanceLevels(Object.class, A.class));
assertEquals(2, CoerceLuaToJava.inheritanceLevels(Object.class, B.class));
assertEquals(3, CoerceLuaToJava.inheritanceLevels(Object.class, C.class));
assertEquals( CoerceLuaToJava.SCORE_UNCOERCIBLE, CoerceLuaToJava.inheritanceLevels(IB.class, A.class) );
assertEquals( CoerceLuaToJava.SCORE_UNCOERCIBLE, CoerceLuaToJava.inheritanceLevels(IC.class, A.class) );
assertEquals( CoerceLuaToJava.SCORE_UNCOERCIBLE, CoerceLuaToJava.inheritanceLevels(IC.class, B.class) );
assertEquals( CoerceLuaToJava.SCORE_UNCOERCIBLE, CoerceLuaToJava.inheritanceLevels(IB.class, IA.class) );
assertEquals( 1, CoerceLuaToJava.inheritanceLevels(IA.class, IB.class) );
assertEquals(CoerceLuaToJava.SCORE_UNCOERCIBLE, CoerceLuaToJava.inheritanceLevels(A.class, Object.class));
assertEquals(CoerceLuaToJava.SCORE_UNCOERCIBLE, CoerceLuaToJava.inheritanceLevels(A.class, String.class));
assertEquals(0, CoerceLuaToJava.inheritanceLevels(A.class, A.class));
assertEquals(1, CoerceLuaToJava.inheritanceLevels(A.class, B.class));
assertEquals(2, CoerceLuaToJava.inheritanceLevels(A.class, C.class));
assertEquals(CoerceLuaToJava.SCORE_UNCOERCIBLE, CoerceLuaToJava.inheritanceLevels(B.class, Object.class));
assertEquals(CoerceLuaToJava.SCORE_UNCOERCIBLE, CoerceLuaToJava.inheritanceLevels(B.class, String.class));
assertEquals(CoerceLuaToJava.SCORE_UNCOERCIBLE, CoerceLuaToJava.inheritanceLevels(B.class, A.class));
assertEquals(0, CoerceLuaToJava.inheritanceLevels(B.class, B.class));
assertEquals(1, CoerceLuaToJava.inheritanceLevels(B.class, C.class));
assertEquals(CoerceLuaToJava.SCORE_UNCOERCIBLE, CoerceLuaToJava.inheritanceLevels(C.class, Object.class));
assertEquals(CoerceLuaToJava.SCORE_UNCOERCIBLE, CoerceLuaToJava.inheritanceLevels(C.class, String.class));
assertEquals(CoerceLuaToJava.SCORE_UNCOERCIBLE, CoerceLuaToJava.inheritanceLevels(C.class, A.class));
assertEquals(CoerceLuaToJava.SCORE_UNCOERCIBLE, CoerceLuaToJava.inheritanceLevels(C.class, B.class));
assertEquals(0, CoerceLuaToJava.inheritanceLevels(C.class, C.class));
}
public void testInterfaceInheritanceLevels() {
assertEquals(1, CoerceLuaToJava.inheritanceLevels(IA.class, A.class));
assertEquals(1, CoerceLuaToJava.inheritanceLevels(IB.class, B.class));
assertEquals(2, CoerceLuaToJava.inheritanceLevels(IA.class, B.class));
assertEquals(1, CoerceLuaToJava.inheritanceLevels(IC.class, C.class));
assertEquals(2, CoerceLuaToJava.inheritanceLevels(IB.class, C.class));
assertEquals(3, CoerceLuaToJava.inheritanceLevels(IA.class, C.class));
assertEquals(1, CoerceLuaToJava.inheritanceLevels(IA.class, D.class));
assertEquals(2, CoerceLuaToJava.inheritanceLevels(IC.class, D.class));
assertEquals(3, CoerceLuaToJava.inheritanceLevels(IB.class, D.class));
assertEquals(CoerceLuaToJava.SCORE_UNCOERCIBLE, CoerceLuaToJava.inheritanceLevels(IB.class, A.class));
assertEquals(CoerceLuaToJava.SCORE_UNCOERCIBLE, CoerceLuaToJava.inheritanceLevels(IC.class, A.class));
assertEquals(CoerceLuaToJava.SCORE_UNCOERCIBLE, CoerceLuaToJava.inheritanceLevels(IC.class, B.class));
assertEquals(CoerceLuaToJava.SCORE_UNCOERCIBLE, CoerceLuaToJava.inheritanceLevels(IB.class, IA.class));
assertEquals(1, CoerceLuaToJava.inheritanceLevels(IA.class, IB.class));
}
public void testCoerceJavaToLuaLuaValue() {
@@ -443,4 +490,3 @@ public class LuaJavaCoercionTest extends TestCase {
assertEquals(LuaValue.valueOf("abcd"), value);
}
}

View File

@@ -6,63 +6,52 @@ import org.luaj.vm2.Globals;
import org.luaj.vm2.LuaValue;
public class LuajavaAccessibleMembersTest extends TestCase {
private Globals globals;
protected void setUp() throws Exception {
super.setUp();
globals = JsePlatform.standardGlobals();
}
protected void setUp() throws Exception {
super.setUp();
globals = JsePlatform.standardGlobals();
}
private String invokeScript(String script) {
try {
private String invokeScript(String script) {
try {
LuaValue c = globals.load(script, "script");
return c.call().tojstring();
} catch ( Exception e ) {
fail("exception: "+e );
return "failed";
}
}
} catch (Exception e) {
fail("exception: " + e);
return "failed";
}
}
public void testAccessFromPrivateClassImplementedMethod() {
assertEquals("privateImpl-aaa-interface_method(bar)", invokeScript(
"b = luajava.newInstance('"+TestClass.class.getName()+"');" +
"a = b:create_PrivateImpl('aaa');" +
"return a:interface_method('bar');"));
assertEquals("privateImpl-aaa-interface_method(bar)",
invokeScript("b = luajava.newInstance('" + TestClass.class.getName() + "');"
+ "a = b:create_PrivateImpl('aaa');" + "return a:interface_method('bar');"));
}
public void testAccessFromPrivateClassPublicMethod() {
assertEquals("privateImpl-aaa-public_method", invokeScript(
"b = luajava.newInstance('"+TestClass.class.getName()+"');" +
"a = b:create_PrivateImpl('aaa');" +
"return a:public_method();"));
assertEquals("privateImpl-aaa-public_method", invokeScript("b = luajava.newInstance('"
+ TestClass.class.getName() + "');" + "a = b:create_PrivateImpl('aaa');" + "return a:public_method();"));
}
public void testAccessFromPrivateClassGetPublicField() {
assertEquals("aaa", invokeScript(
"b = luajava.newInstance('"+TestClass.class.getName()+"');" +
"a = b:create_PrivateImpl('aaa');" +
"return a.public_field;"));
assertEquals("aaa", invokeScript("b = luajava.newInstance('" + TestClass.class.getName() + "');"
+ "a = b:create_PrivateImpl('aaa');" + "return a.public_field;"));
}
public void testAccessFromPrivateClassSetPublicField() {
assertEquals("foo", invokeScript(
"b = luajava.newInstance('"+TestClass.class.getName()+"');" +
"a = b:create_PrivateImpl('aaa');" +
"a.public_field = 'foo';" +
"return a.public_field;"));
assertEquals("foo", invokeScript("b = luajava.newInstance('" + TestClass.class.getName() + "');"
+ "a = b:create_PrivateImpl('aaa');" + "a.public_field = 'foo';" + "return a.public_field;"));
}
public void testAccessFromPrivateClassPublicConstructor() {
assertEquals("privateImpl-constructor", invokeScript(
"b = luajava.newInstance('"+TestClass.class.getName()+"');" +
"c = b:get_PrivateImplClass();" +
"return luajava.new(c);"));
assertEquals("privateImpl-constructor", invokeScript("b = luajava.newInstance('" + TestClass.class.getName()
+ "');" + "c = b:get_PrivateImplClass();" + "return luajava.new(c);"));
}
public void testAccessPublicEnum() {
assertEquals("class org.luaj.vm2.lib.jse.TestClass$SomeEnum", invokeScript(
"b = luajava.newInstance('"+TestClass.class.getName()+"');" +
"return b.SomeEnum"));
assertEquals("class org.luaj.vm2.lib.jse.TestClass$SomeEnum",
invokeScript("b = luajava.newInstance('" + TestClass.class.getName() + "');" + "return b.SomeEnum"));
}
}

View File

@@ -6,172 +6,221 @@ import org.luaj.vm2.LuaError;
import org.luaj.vm2.LuaValue;
public class LuajavaClassMembersTest extends TestCase {
public static class A {
public static class A {
protected A() {}
}
public static class B extends A {
public byte m_byte_field;
public int m_int_field;
public byte m_byte_field;
public int m_int_field;
public double m_double_field;
public String m_string_field;
protected B() {}
public B(int i) { m_int_field = i; }
public String setString( String x ) { return "setString(String) "+x; }
public String setString(String x) { return "setString(String) " + x; }
public String getString() { return "abc"; }
public int getint() { return 100000; }
public String uniq() { return "uniq()"; }
public String uniqs(String s) { return "uniqs(string:"+s+")"; }
public String uniqi(int i) { return "uniqi(int:"+i+")"; }
public String uniqsi(String s, int i) { return "uniqsi(string:"+s+",int:"+i+")"; }
public String uniqis(int i, String s) { return "uniqis(int:"+i+",string:"+s+")"; }
public String pick() { return "pick()"; }
public String pick(String s) { return "pick(string:"+s+")"; }
public String pick(int i) { return "pick(int:"+i+")"; }
public String pick(String s, int i) { return "pick(string:"+s+",int:"+i+")"; }
public String pick(int i, String s) { return "pick(int:"+i+",string:"+s+")"; }
public static String staticpick() { return "static-pick()"; }
public static String staticpick(String s) { return "static-pick(string:"+s+")"; }
public static String staticpick(int i) { return "static-pick(int:"+i+")"; }
public static String staticpick(String s, int i) { return "static-pick(string:"+s+",int:"+i+")"; }
public static String staticpick(int i, String s) { return "static-pick(int:"+i+",string:"+s+")"; }
public String uniq() { return "uniq()"; }
public String uniqs(String s) { return "uniqs(string:" + s + ")"; }
public String uniqi(int i) { return "uniqi(int:" + i + ")"; }
public String uniqsi(String s, int i) { return "uniqsi(string:" + s + ",int:" + i + ")"; }
public String uniqis(int i, String s) { return "uniqis(int:" + i + ",string:" + s + ")"; }
public String pick() { return "pick()"; }
public String pick(String s) { return "pick(string:" + s + ")"; }
public String pick(int i) { return "pick(int:" + i + ")"; }
public String pick(String s, int i) { return "pick(string:" + s + ",int:" + i + ")"; }
public String pick(int i, String s) { return "pick(int:" + i + ",string:" + s + ")"; }
public static String staticpick() { return "static-pick()"; }
public static String staticpick(String s) { return "static-pick(string:" + s + ")"; }
public static String staticpick(int i) { return "static-pick(int:" + i + ")"; }
public static String staticpick(String s, int i) { return "static-pick(string:" + s + ",int:" + i + ")"; }
public static String staticpick(int i, String s) { return "static-pick(int:" + i + ",string:" + s + ")"; }
}
public static class C extends B {
public C() {}
public C(String s) { m_string_field = s; }
public C(int i) { m_int_field = i; }
public C(String s, int i) { m_string_field = s; m_int_field = i; }
public int getint() { return 200000; }
public String pick(String s) { return "class-c-pick(string:"+s+")"; }
public String pick(int i) { return "class-c-pick(int:"+i+")"; }
public String pick(String s) { return "class-c-pick(string:" + s + ")"; }
public String pick(int i) { return "class-c-pick(int:" + i + ")"; }
public static class D {
public static String name() { return "name-of-D"; }
public static String name() { return "name-of-D"; }
}
}
static LuaValue ZERO = LuaValue.ZERO;
static LuaValue ONE = LuaValue.ONE;
static LuaValue PI = LuaValue.valueOf(Math.PI);
static LuaValue ZERO = LuaValue.ZERO;
static LuaValue ONE = LuaValue.ONE;
static LuaValue PI = LuaValue.valueOf(Math.PI);
static LuaValue THREE = LuaValue.valueOf(3);
static LuaValue NUMS = LuaValue.valueOf(123);
static LuaValue ABC = LuaValue.valueOf("abc");
static LuaValue NUMS = LuaValue.valueOf(123);
static LuaValue ABC = LuaValue.valueOf("abc");
static LuaValue SOMEA = CoerceJavaToLua.coerce(new A());
static LuaValue SOMEB = CoerceJavaToLua.coerce(new B());
static LuaValue SOMEC = CoerceJavaToLua.coerce(new C());
public void testSetByteField() {
B b = new B();
JavaInstance i = new JavaInstance(b);
i.set("m_byte_field", ONE ); assertEquals( 1, b.m_byte_field ); assertEquals( ONE, i.get("m_byte_field") );
i.set("m_byte_field", PI ); assertEquals( 3, b.m_byte_field ); assertEquals( THREE, i.get("m_byte_field") );
i.set("m_byte_field", ABC ); assertEquals( 0, b.m_byte_field ); assertEquals( ZERO, i.get("m_byte_field") );
}
i.set("m_byte_field", ONE);
assertEquals(1, b.m_byte_field);
assertEquals(ONE, i.get("m_byte_field"));
i.set("m_byte_field", PI);
assertEquals(3, b.m_byte_field);
assertEquals(THREE, i.get("m_byte_field"));
i.set("m_byte_field", ABC);
assertEquals(0, b.m_byte_field);
assertEquals(ZERO, i.get("m_byte_field"));
}
public void testSetDoubleField() {
B b = new B();
JavaInstance i = new JavaInstance(b);
i.set("m_double_field", ONE ); assertEquals( 1., b.m_double_field ); assertEquals( ONE, i.get("m_double_field") );
i.set("m_double_field", PI ); assertEquals( Math.PI, b.m_double_field ); assertEquals( PI, i.get("m_double_field") );
i.set("m_double_field", ABC ); assertEquals( 0., b.m_double_field ); assertEquals( ZERO, i.get("m_double_field") );
i.set("m_double_field", ONE);
assertEquals(1., b.m_double_field);
assertEquals(ONE, i.get("m_double_field"));
i.set("m_double_field", PI);
assertEquals(Math.PI, b.m_double_field);
assertEquals(PI, i.get("m_double_field"));
i.set("m_double_field", ABC);
assertEquals(0., b.m_double_field);
assertEquals(ZERO, i.get("m_double_field"));
}
public void testNoFactory() {
JavaClass c = JavaClass.forClass(A.class);
try {
c.call();
fail( "did not throw lua error as expected" );
} catch ( LuaError e ) {
fail("did not throw lua error as expected");
} catch (LuaError e) {
}
}
public void testUniqueFactoryCoercible() {
JavaClass c = JavaClass.forClass(B.class);
assertEquals( JavaClass.class, c.getClass() );
assertEquals(JavaClass.class, c.getClass());
LuaValue constr = c.get("new");
assertEquals( JavaConstructor.class, constr.getClass() );
assertEquals(JavaConstructor.class, constr.getClass());
LuaValue v = constr.call(NUMS);
Object b = v.touserdata();
assertEquals( B.class, b.getClass() );
assertEquals( 123, ((B)b).m_int_field );
assertEquals(B.class, b.getClass());
assertEquals(123, ((B) b).m_int_field);
Object b0 = constr.call().touserdata();
assertEquals( B.class, b0.getClass() );
assertEquals( 0, ((B)b0).m_int_field );
assertEquals(B.class, b0.getClass());
assertEquals(0, ((B) b0).m_int_field);
}
public void testUniqueFactoryUncoercible() {
JavaClass f = JavaClass.forClass(B.class);
LuaValue constr = f.get("new");
assertEquals( JavaConstructor.class, constr.getClass() );
try {
assertEquals(JavaConstructor.class, constr.getClass());
try {
LuaValue v = constr.call(LuaValue.userdataOf(new Object()));
Object b = v.touserdata();
// fail( "did not throw lua error as expected" );
assertEquals( 0, ((B)b).m_int_field );
} catch ( LuaError e ) {
assertEquals(0, ((B) b).m_int_field);
} catch (LuaError e) {
}
}
public void testOverloadedFactoryCoercible() {
JavaClass f = JavaClass.forClass(C.class);
LuaValue constr = f.get("new");
assertEquals( JavaConstructor.Overload.class, constr.getClass() );
assertEquals(JavaConstructor.Overload.class, constr.getClass());
Object c = constr.call().touserdata();
Object ci = constr.call(LuaValue.valueOf(123)).touserdata();
Object cs = constr.call(LuaValue.valueOf("abc")).touserdata();
Object csi = constr.call( LuaValue.valueOf("def"), LuaValue.valueOf(456) ).touserdata();
assertEquals( C.class, c.getClass() );
assertEquals( C.class, ci.getClass() );
assertEquals( C.class, cs.getClass() );
assertEquals( C.class, csi.getClass() );
assertEquals( null, ((C)c).m_string_field );
assertEquals( 0, ((C)c).m_int_field );
assertEquals( "abc", ((C)cs).m_string_field );
assertEquals( 0, ((C)cs).m_int_field );
assertEquals( null, ((C)ci).m_string_field );
assertEquals( 123, ((C)ci).m_int_field );
assertEquals( "def", ((C)csi).m_string_field );
assertEquals( 456, ((C)csi).m_int_field );
Object csi = constr.call(LuaValue.valueOf("def"), LuaValue.valueOf(456)).touserdata();
assertEquals(C.class, c.getClass());
assertEquals(C.class, ci.getClass());
assertEquals(C.class, cs.getClass());
assertEquals(C.class, csi.getClass());
assertEquals(null, ((C) c).m_string_field);
assertEquals(0, ((C) c).m_int_field);
assertEquals("abc", ((C) cs).m_string_field);
assertEquals(0, ((C) cs).m_int_field);
assertEquals(null, ((C) ci).m_string_field);
assertEquals(123, ((C) ci).m_int_field);
assertEquals("def", ((C) csi).m_string_field);
assertEquals(456, ((C) csi).m_int_field);
}
public void testOverloadedFactoryUncoercible() {
JavaClass f = JavaClass.forClass(C.class);
try {
Object c = f.call(LuaValue.userdataOf(new Object()));
try {
Object c = f.call(LuaValue.userdataOf(new Object()));
// fail( "did not throw lua error as expected" );
assertEquals( 0, ((C)c).m_int_field );
assertEquals( null, ((C)c).m_string_field );
} catch ( LuaError e ) {
assertEquals(0, ((C) c).m_int_field);
assertEquals(null, ((C) c).m_string_field);
} catch (LuaError e) {
}
}
public void testNoAttribute() {
JavaClass f = JavaClass.forClass(A.class);
LuaValue v = f.get("bogus");
assertEquals( v, LuaValue.NIL );
try {
f.set("bogus",ONE);
fail( "did not throw lua error as expected" );
} catch ( LuaError e ) {}
assertEquals(v, LuaValue.NIL);
try {
f.set("bogus", ONE);
fail("did not throw lua error as expected");
} catch (LuaError e) {
}
}
public void testFieldAttributeCoercible() {
JavaInstance i = new JavaInstance(new B());
i.set("m_int_field", ONE ); assertEquals( 1, i.get("m_int_field").toint() );
i.set("m_int_field", THREE ); assertEquals( 3, i.get("m_int_field").toint() );
i.set("m_int_field", ONE);
assertEquals(1, i.get("m_int_field").toint());
i.set("m_int_field", THREE);
assertEquals(3, i.get("m_int_field").toint());
i = new JavaInstance(new C());
i.set("m_int_field", ONE ); assertEquals( 1, i.get("m_int_field").toint() );
i.set("m_int_field", THREE ); assertEquals( 3, i.get("m_int_field").toint() );
i.set("m_int_field", ONE);
assertEquals(1, i.get("m_int_field").toint());
i.set("m_int_field", THREE);
assertEquals(3, i.get("m_int_field").toint());
}
public void testUniqueMethodAttributeCoercible() {
B b = new B();
JavaInstance ib = new JavaInstance(b);
LuaValue b_getString = ib.get("getString");
LuaValue b_getint = ib.get("getint");
assertEquals( JavaMethod.class, b_getString.getClass() );
assertEquals( JavaMethod.class, b_getint.getClass() );
assertEquals( "abc", b_getString.call(SOMEB).tojstring() );
assertEquals( 100000, b_getint.call(SOMEB).toint());
assertEquals( "abc", b_getString.call(SOMEC).tojstring() );
assertEquals( 200000, b_getint.call(SOMEC).toint());
assertEquals(JavaMethod.class, b_getString.getClass());
assertEquals(JavaMethod.class, b_getint.getClass());
assertEquals("abc", b_getString.call(SOMEB).tojstring());
assertEquals(100000, b_getint.call(SOMEB).toint());
assertEquals("abc", b_getString.call(SOMEC).tojstring());
assertEquals(200000, b_getint.call(SOMEC).toint());
}
public void testUniqueMethodAttributeArgsCoercible() {
B b = new B();
JavaInstance ib = new JavaInstance(b);
@@ -180,52 +229,60 @@ public class LuajavaClassMembersTest extends TestCase {
LuaValue uniqi = ib.get("uniqi");
LuaValue uniqsi = ib.get("uniqsi");
LuaValue uniqis = ib.get("uniqis");
assertEquals( JavaMethod.class, uniq.getClass() );
assertEquals( JavaMethod.class, uniqs.getClass() );
assertEquals( JavaMethod.class, uniqi.getClass() );
assertEquals( JavaMethod.class, uniqsi.getClass() );
assertEquals( JavaMethod.class, uniqis.getClass() );
assertEquals( "uniq()", uniq.call(SOMEB).tojstring() );
assertEquals( "uniqs(string:abc)", uniqs.call(SOMEB,ABC).tojstring() );
assertEquals( "uniqi(int:1)", uniqi.call(SOMEB,ONE).tojstring() );
assertEquals( "uniqsi(string:abc,int:1)", uniqsi.call(SOMEB,ABC,ONE).tojstring() );
assertEquals( "uniqis(int:1,string:abc)", uniqis.call(SOMEB,ONE,ABC).tojstring() );
assertEquals( "uniqis(int:1,string:abc)", uniqis.invoke(LuaValue.varargsOf(new LuaValue[] {SOMEB,ONE,ABC,ONE})).arg1().tojstring() );
assertEquals(JavaMethod.class, uniq.getClass());
assertEquals(JavaMethod.class, uniqs.getClass());
assertEquals(JavaMethod.class, uniqi.getClass());
assertEquals(JavaMethod.class, uniqsi.getClass());
assertEquals(JavaMethod.class, uniqis.getClass());
assertEquals("uniq()", uniq.call(SOMEB).tojstring());
assertEquals("uniqs(string:abc)", uniqs.call(SOMEB, ABC).tojstring());
assertEquals("uniqi(int:1)", uniqi.call(SOMEB, ONE).tojstring());
assertEquals("uniqsi(string:abc,int:1)", uniqsi.call(SOMEB, ABC, ONE).tojstring());
assertEquals("uniqis(int:1,string:abc)", uniqis.call(SOMEB, ONE, ABC).tojstring());
assertEquals("uniqis(int:1,string:abc)",
uniqis.invoke(LuaValue.varargsOf(new LuaValue[] { SOMEB, ONE, ABC, ONE })).arg1().tojstring());
}
public void testOverloadedMethodAttributeCoercible() {
B b = new B();
JavaInstance ib = new JavaInstance(b);
LuaValue p = ib.get("pick");
assertEquals( "pick()", p.call(SOMEB).tojstring() );
assertEquals( "pick(string:abc)", p.call(SOMEB,ABC).tojstring() );
assertEquals( "pick(int:1)", p.call(SOMEB,ONE).tojstring() );
assertEquals( "pick(string:abc,int:1)", p.call(SOMEB,ABC,ONE).tojstring() );
assertEquals( "pick(int:1,string:abc)", p.call(SOMEB,ONE,ABC).tojstring() );
assertEquals( "pick(int:1,string:abc)", p.invoke(LuaValue.varargsOf(new LuaValue[] {SOMEB,ONE,ABC,ONE})).arg1().tojstring() );
assertEquals("pick()", p.call(SOMEB).tojstring());
assertEquals("pick(string:abc)", p.call(SOMEB, ABC).tojstring());
assertEquals("pick(int:1)", p.call(SOMEB, ONE).tojstring());
assertEquals("pick(string:abc,int:1)", p.call(SOMEB, ABC, ONE).tojstring());
assertEquals("pick(int:1,string:abc)", p.call(SOMEB, ONE, ABC).tojstring());
assertEquals("pick(int:1,string:abc)",
p.invoke(LuaValue.varargsOf(new LuaValue[] { SOMEB, ONE, ABC, ONE })).arg1().tojstring());
}
public void testUnboundOverloadedMethodAttributeCoercible() {
B b = new B();
JavaInstance ib = new JavaInstance(b);
LuaValue p = ib.get("pick");
assertEquals( JavaMethod.Overload.class, p.getClass() );
assertEquals( "pick()", p.call(SOMEC).tojstring() );
assertEquals( "class-c-pick(string:abc)", p.call(SOMEC,ABC).tojstring() );
assertEquals( "class-c-pick(int:1)", p.call(SOMEC,ONE).tojstring() );
assertEquals( "pick(string:abc,int:1)", p.call(SOMEC,ABC,ONE).tojstring() );
assertEquals( "pick(int:1,string:abc)", p.call(SOMEC,ONE,ABC).tojstring() );
assertEquals( "pick(int:1,string:abc)", p.invoke(LuaValue.varargsOf(new LuaValue[] {SOMEC,ONE,ABC,ONE})).arg1().tojstring() );
assertEquals(JavaMethod.Overload.class, p.getClass());
assertEquals("pick()", p.call(SOMEC).tojstring());
assertEquals("class-c-pick(string:abc)", p.call(SOMEC, ABC).tojstring());
assertEquals("class-c-pick(int:1)", p.call(SOMEC, ONE).tojstring());
assertEquals("pick(string:abc,int:1)", p.call(SOMEC, ABC, ONE).tojstring());
assertEquals("pick(int:1,string:abc)", p.call(SOMEC, ONE, ABC).tojstring());
assertEquals("pick(int:1,string:abc)",
p.invoke(LuaValue.varargsOf(new LuaValue[] { SOMEC, ONE, ABC, ONE })).arg1().tojstring());
}
public void testOverloadedStaticMethodAttributeCoercible() {
B b = new B();
JavaInstance ib = new JavaInstance(b);
LuaValue p = ib.get("staticpick");
assertEquals( "static-pick()", p.call(SOMEB).tojstring() );
assertEquals( "static-pick(string:abc)", p.call(SOMEB,ABC).tojstring() );
assertEquals( "static-pick(int:1)", p.call(SOMEB,ONE).tojstring() );
assertEquals( "static-pick(string:abc,int:1)", p.call(SOMEB,ABC,ONE).tojstring() );
assertEquals( "static-pick(int:1,string:abc)", p.call(SOMEB,ONE,ABC).tojstring() );
assertEquals( "static-pick(int:1,string:abc)", p.invoke(LuaValue.varargsOf(new LuaValue[] {SOMEB,ONE,ABC,ONE})).arg1().tojstring() );
assertEquals("static-pick()", p.call(SOMEB).tojstring());
assertEquals("static-pick(string:abc)", p.call(SOMEB, ABC).tojstring());
assertEquals("static-pick(int:1)", p.call(SOMEB, ONE).tojstring());
assertEquals("static-pick(string:abc,int:1)", p.call(SOMEB, ABC, ONE).tojstring());
assertEquals("static-pick(int:1,string:abc)", p.call(SOMEB, ONE, ABC).tojstring());
assertEquals("static-pick(int:1,string:abc)",
p.invoke(LuaValue.varargsOf(new LuaValue[] { SOMEB, ONE, ABC, ONE })).arg1().tojstring());
}
public void testGetInnerClass() {
C c = new C();
JavaInstance ic = new JavaInstance(c);

View File

@@ -10,53 +10,85 @@ public class OsLibTest extends TestCase {
LuaValue jme_lib;
LuaValue jse_lib;
double time;
double time;
public void setUp() {
jse_lib = JsePlatform.standardGlobals().get("os");;
jme_lib = JmePlatform.standardGlobals().get("os");;
time = new java.util.Date(2001-1900, 7, 23, 14, 55, 02).getTime() / 1000.0;
jse_lib = JsePlatform.standardGlobals().get("os");
;
jme_lib = JmePlatform.standardGlobals().get("os");
;
time = new java.util.Date(2001-1900, 7, 23, 14, 55, 02).getTime()/1000.0;
}
void t(String format, String expected) {
String actual = jme_lib.get("date").call(LuaValue.valueOf(format), LuaValue.valueOf(time)).tojstring();
assertEquals(expected, actual);
}
public void testStringDateChars() { t("foo", "foo"); }
public void testStringDate_a() { t("%a", "Thu"); }
public void testStringDate_A() { t("%A", "Thursday"); }
public void testStringDate_b() { t("%b", "Aug"); }
public void testStringDate_B() { t("%B", "August"); }
public void testStringDate_c() { t("%c", "Thu Aug 23 14:55:02 2001"); }
public void testStringDate_d() { t("%d", "23"); }
public void testStringDate_H() { t("%H", "14"); }
public void testStringDate_I() { t("%I", "02"); }
public void testStringDate_j() { t("%j", "235"); }
public void testStringDate_m() { t("%m", "08"); }
public void testStringDate_M() { t("%M", "55"); }
public void testStringDate_p() { t("%p", "PM"); }
public void testStringDate_S() { t("%S", "02"); }
public void testStringDate_U() { t("%U", "33"); }
public void testStringDate_w() { t("%w", "4"); }
public void testStringDate_W() { t("%W", "34"); }
public void testStringDate_x() { t("%x", "08/23/01"); }
public void testStringDate_X() { t("%X", "14:55:02"); }
public void testStringDate_y() { t("%y", "01"); }
public void testStringDate_Y() { t("%Y", "2001"); }
public void testStringDate_Pct() { t("%%", "%"); }
static final double DAY = 24. * 3600.;
public void testStringDate_UW_neg4() { time-=4*DAY; t("%c %U %W", "Sun Aug 19 14:55:02 2001 33 33"); }
public void testStringDate_UW_neg3() { time-=3*DAY; t("%c %U %W", "Mon Aug 20 14:55:02 2001 33 34"); }
public void testStringDate_UW_neg2() { time-=2*DAY; t("%c %U %W", "Tue Aug 21 14:55:02 2001 33 34"); }
public void testStringDate_UW_neg1() { time-=DAY; t("%c %U %W", "Wed Aug 22 14:55:02 2001 33 34"); }
public void testStringDate_UW_pos0() { time+=0; t("%c %U %W", "Thu Aug 23 14:55:02 2001 33 34"); }
public void testStringDate_UW_pos1() { time+=DAY; t("%c %U %W", "Fri Aug 24 14:55:02 2001 33 34"); }
public void testStringDate_UW_pos2() { time+=2*DAY; t("%c %U %W", "Sat Aug 25 14:55:02 2001 33 34"); }
public void testStringDate_UW_pos3() { time+=3*DAY; t("%c %U %W", "Sun Aug 26 14:55:02 2001 34 34"); }
public void testStringDate_UW_pos4() { time+=4*DAY; t("%c %U %W", "Mon Aug 27 14:55:02 2001 34 35"); }
public void testStringDateChars() { t("foo", "foo"); }
public void testStringDate_a() { t("%a", "Thu"); }
public void testStringDate_A() { t("%A", "Thursday"); }
public void testStringDate_b() { t("%b", "Aug"); }
public void testStringDate_B() { t("%B", "August"); }
public void testStringDate_c() { t("%c", "Thu Aug 23 14:55:02 2001"); }
public void testStringDate_d() { t("%d", "23"); }
public void testStringDate_H() { t("%H", "14"); }
public void testStringDate_I() { t("%I", "02"); }
public void testStringDate_j() { t("%j", "235"); }
public void testStringDate_m() { t("%m", "08"); }
public void testStringDate_M() { t("%M", "55"); }
public void testStringDate_p() { t("%p", "PM"); }
public void testStringDate_S() { t("%S", "02"); }
public void testStringDate_U() { t("%U", "33"); }
public void testStringDate_w() { t("%w", "4"); }
public void testStringDate_W() { t("%W", "34"); }
public void testStringDate_x() { t("%x", "08/23/01"); }
public void testStringDate_X() { t("%X", "14:55:02"); }
public void testStringDate_y() { t("%y", "01"); }
public void testStringDate_Y() { t("%Y", "2001"); }
public void testStringDate_Pct() { t("%%", "%"); }
static final double DAY = 24.*3600.;
public void testStringDate_UW_neg4() { time -= 4*DAY; t("%c %U %W", "Sun Aug 19 14:55:02 2001 33 33"); }
public void testStringDate_UW_neg3() { time -= 3*DAY; t("%c %U %W", "Mon Aug 20 14:55:02 2001 33 34"); }
public void testStringDate_UW_neg2() { time -= 2*DAY; t("%c %U %W", "Tue Aug 21 14:55:02 2001 33 34"); }
public void testStringDate_UW_neg1() { time -= DAY; t("%c %U %W", "Wed Aug 22 14:55:02 2001 33 34"); }
public void testStringDate_UW_pos0() { time += 0; t("%c %U %W", "Thu Aug 23 14:55:02 2001 33 34"); }
public void testStringDate_UW_pos1() { time += DAY; t("%c %U %W", "Fri Aug 24 14:55:02 2001 33 34"); }
public void testStringDate_UW_pos2() { time += 2*DAY; t("%c %U %W", "Sat Aug 25 14:55:02 2001 33 34"); }
public void testStringDate_UW_pos3() { time += 3*DAY; t("%c %U %W", "Sun Aug 26 14:55:02 2001 34 34"); }
public void testStringDate_UW_pos4() { time += 4*DAY; t("%c %U %W", "Mon Aug 27 14:55:02 2001 34 35"); }
public void testJseOsGetenvForEnvVariables() {
LuaValue USER = LuaValue.valueOf("USER");
LuaValue jse_user = jse_lib.get("getenv").call(USER);

View File

@@ -1,22 +1,31 @@
package org.luaj.vm2.lib.jse;
public class TestClass {
private static class PrivateImpl implements TestInterface {
private static class PrivateImpl implements TestInterface {
public String public_field;
public PrivateImpl() {
this.public_field = "privateImpl-constructor";
}
PrivateImpl(String f) {
PrivateImpl(String f) {
this.public_field = f;
}
public String public_method() { return "privateImpl-"+public_field+"-public_method"; }
public String interface_method(String x) { return "privateImpl-"+public_field+"-interface_method("+x+")"; }
public String public_method() { return "privateImpl-" + public_field + "-public_method"; }
public String interface_method(String x) {
return "privateImpl-" + public_field + "-interface_method(" + x + ")";
}
public String toString() { return public_field; }
}
public TestInterface create_PrivateImpl(String f) { return new PrivateImpl(f); }
public Class get_PrivateImplClass() { return PrivateImpl.class; }
public enum SomeEnum {
ValueOne,
ValueTwo,
}
}
}
public TestInterface create_PrivateImpl(String f) { return new PrivateImpl(f); }
public Class get_PrivateImplClass() { return PrivateImpl.class; }
public enum SomeEnum {
ValueOne, ValueTwo,
}
}

View File

@@ -1,5 +1,5 @@
package org.luaj.vm2.lib.jse;
public interface TestInterface {
public interface TestInterface {
String interface_method(String x);
}
}

View File

@@ -3,15 +3,16 @@ package org.luaj.vm2.require;
import org.luaj.vm2.LuaValue;
/**
* This should fail while trying to load via "require() because it is not a LibFunction"
* This should fail while trying to load via "require() because it is not a
* LibFunction"
*
*/
public class RequireSampleClassCastExcep {
public RequireSampleClassCastExcep() {
public RequireSampleClassCastExcep() {
}
public LuaValue call() {
return LuaValue.valueOf("require-sample-class-cast-excep");
}
}
}

View File

@@ -4,17 +4,17 @@ import org.luaj.vm2.LuaValue;
import org.luaj.vm2.lib.ZeroArgFunction;
/**
* This should fail while trying to load via
* "require()" because it throws a LuaError
* This should fail while trying to load via "require()" because it throws a
* LuaError
*
*/
public class RequireSampleLoadLuaError extends ZeroArgFunction {
public RequireSampleLoadLuaError() {
public RequireSampleLoadLuaError() {
}
public LuaValue call() {
error("sample-load-lua-error");
return LuaValue.valueOf("require-sample-load-lua-error");
}
}
}

View File

@@ -4,15 +4,16 @@ import org.luaj.vm2.LuaValue;
import org.luaj.vm2.lib.ZeroArgFunction;
/**
* This should fail while trying to load via "require()" because it throws a RuntimeException
* This should fail while trying to load via "require()" because it throws a
* RuntimeException
*
*/
public class RequireSampleLoadRuntimeExcep extends ZeroArgFunction {
public RequireSampleLoadRuntimeExcep() {
public RequireSampleLoadRuntimeExcep() {
}
public LuaValue call() {
throw new RuntimeException("sample-load-runtime-exception");
}
}
}

View File

@@ -4,15 +4,16 @@ import org.luaj.vm2.LuaValue;
import org.luaj.vm2.lib.TwoArgFunction;
/**
* This should succeed as a library that can be loaded dynamically via "require()"
* This should succeed as a library that can be loaded dynamically via
* "require()"
*/
public class RequireSampleSuccess extends TwoArgFunction {
public RequireSampleSuccess() {
public RequireSampleSuccess() {
}
public LuaValue call(LuaValue modname, LuaValue env) {
env.checkglobals();
return LuaValue.valueOf("require-sample-success-"+modname.tojstring());
}
return LuaValue.valueOf("require-sample-success-" + modname.tojstring());
}
}

View File

@@ -42,46 +42,49 @@ import org.luaj.vm2.LuaFunction;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.lib.OneArgFunction;
public class ScriptEngineTests extends TestSuite {
public class ScriptEngineTests extends TestSuite {
public static TestSuite suite() {
TestSuite suite = new TestSuite("Script Engine Tests");
suite.addTest( new TestSuite( LookupEngineTestCase.class, "Lookup Engine" ) );
suite.addTest( new TestSuite( DefaultBindingsTest.class, "Default Bindings" ) );
suite.addTest( new TestSuite( SimpleBindingsTest.class, "Simple Bindings" ) );
suite.addTest( new TestSuite( CompileClosureTest.class, "Compile Closure" ) );
suite.addTest( new TestSuite( CompileNonClosureTest.class, "Compile NonClosure" ) );
suite.addTest( new TestSuite( UserContextTest.class, "User Context" ) );
suite.addTest( new TestSuite( WriterTest.class, "Writer" ) );
suite.addTest(new TestSuite(LookupEngineTestCase.class, "Lookup Engine"));
suite.addTest(new TestSuite(DefaultBindingsTest.class, "Default Bindings"));
suite.addTest(new TestSuite(SimpleBindingsTest.class, "Simple Bindings"));
suite.addTest(new TestSuite(CompileClosureTest.class, "Compile Closure"));
suite.addTest(new TestSuite(CompileNonClosureTest.class, "Compile NonClosure"));
suite.addTest(new TestSuite(UserContextTest.class, "User Context"));
suite.addTest(new TestSuite(WriterTest.class, "Writer"));
return suite;
}
public static class LookupEngineTestCase extends TestCase {
public static class LookupEngineTestCase extends TestCase {
public void testGetEngineByExtension() {
ScriptEngine e = new ScriptEngineManager().getEngineByExtension(".lua");
assertNotNull(e);
assertEquals(LuaScriptEngine.class, e.getClass());
ScriptEngine e = new ScriptEngineManager().getEngineByExtension(".lua");
assertNotNull(e);
assertEquals(LuaScriptEngine.class, e.getClass());
}
public void testGetEngineByName() {
ScriptEngine e = new ScriptEngineManager().getEngineByName("luaj");
assertNotNull(e);
assertEquals(LuaScriptEngine.class, e.getClass());
ScriptEngine e = new ScriptEngineManager().getEngineByName("luaj");
assertNotNull(e);
assertEquals(LuaScriptEngine.class, e.getClass());
}
public void testGetEngineByMimeType() {
ScriptEngine e = new ScriptEngineManager().getEngineByMimeType("text/lua");
assertNotNull(e);
assertEquals(LuaScriptEngine.class, e.getClass());
ScriptEngine e = new ScriptEngineManager().getEngineByMimeType("text/lua");
assertNotNull(e);
assertEquals(LuaScriptEngine.class, e.getClass());
}
public void testFactoryMetadata() {
ScriptEngine e = new ScriptEngineManager().getEngineByName("luaj");
ScriptEngineFactory f = e.getFactory();
assertEquals("Luaj", f.getEngineName());
assertEquals("Luaj 0.0", f.getEngineVersion());
assertEquals("lua", f.getLanguageName());
assertEquals("5.2", f.getLanguageVersion());
ScriptEngine e = new ScriptEngineManager().getEngineByName("luaj");
ScriptEngineFactory f = e.getFactory();
assertEquals("Luaj", f.getEngineName());
assertEquals("Luaj 0.0", f.getEngineVersion());
assertEquals("lua", f.getLanguageName());
assertEquals("5.2", f.getLanguageVersion());
}
}
public static class DefaultBindingsTest extends EngineTestCase {
protected Bindings createBindings() {
return e.createBindings();
@@ -99,213 +102,233 @@ public class ScriptEngineTests extends TestSuite {
System.setProperty("org.luaj.luajc", "false");
super.setUp();
}
public void testCompiledFunctionIsClosure() throws ScriptException {
CompiledScript cs = ((Compilable)e).compile("return 'foo'");
LuaValue value = ((LuaScriptEngine.LuajCompiledScript)cs).function;
assertTrue(value.isclosure());
CompiledScript cs = ((Compilable) e).compile("return 'foo'");
LuaValue value = ((LuaScriptEngine.LuajCompiledScript) cs).function;
assertTrue(value.isclosure());
}
}
public static class CompileNonClosureTest extends DefaultBindingsTest {
protected void setUp() throws Exception {
System.setProperty("org.luaj.luajc", "true");
super.setUp();
}
public void testCompiledFunctionIsNotClosure() throws ScriptException {
CompiledScript cs = ((Compilable)e).compile("return 'foo'");
LuaValue value = ((LuaScriptEngine.LuajCompiledScript)cs).function;
assertFalse(value.isclosure());
CompiledScript cs = ((Compilable) e).compile("return 'foo'");
LuaValue value = ((LuaScriptEngine.LuajCompiledScript) cs).function;
assertFalse(value.isclosure());
}
}
abstract public static class EngineTestCase extends TestCase {
abstract public static class EngineTestCase extends TestCase {
protected ScriptEngine e;
protected Bindings b;
protected Bindings b;
abstract protected Bindings createBindings();
protected void setUp() throws Exception {
this.e = new ScriptEngineManager().getEngineByName("luaj");
this.e = new ScriptEngineManager().getEngineByName("luaj");
this.b = createBindings();
}
public void testSqrtIntResult() throws ScriptException {
e.put("x", 25);
e.eval("y = math.sqrt(x)");
Object y = e.get("y");
assertEquals(5, y);
e.put("x", 25);
e.eval("y = math.sqrt(x)");
Object y = e.get("y");
assertEquals(5, y);
}
public void testOneArgFunction() throws ScriptException {
e.put("x", 25);
e.eval("y = math.sqrt(x)");
Object y = e.get("y");
assertEquals(5, y);
e.put("f", new OneArgFunction() {
public LuaValue call(LuaValue arg) {
return LuaValue.valueOf(arg.toString()+"123");
}
});
Object r = e.eval("return f('abc')");
assertEquals("abc123", r);
e.put("x", 25);
e.eval("y = math.sqrt(x)");
Object y = e.get("y");
assertEquals(5, y);
e.put("f", new OneArgFunction() {
public LuaValue call(LuaValue arg) {
return LuaValue.valueOf(arg.toString() + "123");
}
});
Object r = e.eval("return f('abc')");
assertEquals("abc123", r);
}
public void testCompiledScript() throws ScriptException {
CompiledScript cs = ((Compilable)e).compile("y = math.sqrt(x); return y");
b.put("x", 144);
assertEquals(12, cs.eval(b));
CompiledScript cs = ((Compilable) e).compile("y = math.sqrt(x); return y");
b.put("x", 144);
assertEquals(12, cs.eval(b));
}
public void testBuggyLuaScript() {
try {
e.eval("\n\nbuggy lua code\n\n");
} catch ( ScriptException se ) {
assertEquals("eval threw javax.script.ScriptException: [string \"script\"]:3: syntax error", se.getMessage());
return;
}
fail("buggy script did not throw ScriptException as expected.");
try {
e.eval("\n\nbuggy lua code\n\n");
} catch (ScriptException se) {
assertEquals("eval threw javax.script.ScriptException: [string \"script\"]:3: syntax error",
se.getMessage());
return;
}
fail("buggy script did not throw ScriptException as expected.");
}
public void testScriptRedirection() throws ScriptException {
Reader input = new CharArrayReader("abcdefg\nhijk".toCharArray());
CharArrayWriter output = new CharArrayWriter();
CharArrayWriter errors = new CharArrayWriter();
String script =
"print(\"string written using 'print'\")\n" +
"io.write(\"string written using 'io.write()'\\n\")\n" +
"io.stdout:write(\"string written using 'io.stdout:write()'\\n\")\n" +
"io.stderr:write(\"string written using 'io.stderr:write()'\\n\")\n" +
"io.write([[string read using 'io.stdin:read(\"*l\")':]]..io.stdin:read(\"*l\")..\"\\n\")\n";
Reader input = new CharArrayReader("abcdefg\nhijk".toCharArray());
CharArrayWriter output = new CharArrayWriter();
CharArrayWriter errors = new CharArrayWriter();
String script = "print(\"string written using 'print'\")\n"
+ "io.write(\"string written using 'io.write()'\\n\")\n"
+ "io.stdout:write(\"string written using 'io.stdout:write()'\\n\")\n"
+ "io.stderr:write(\"string written using 'io.stderr:write()'\\n\")\n"
+ "io.write([[string read using 'io.stdin:read(\"*l\")':]]..io.stdin:read(\"*l\")..\"\\n\")\n";
// Evaluate script with redirection set
e.getContext().setReader(input);
e.getContext().setWriter(output);
e.getContext().setErrorWriter(errors);
e.eval(script);
final String expectedOutput = "string written using 'print'\n"+
"string written using 'io.write()'\n"+
"string written using 'io.stdout:write()'\n"+
"string read using 'io.stdin:read(\"*l\")':abcdefg\n";
assertEquals(expectedOutput, output.toString());
final String expectedErrors = "string written using 'io.stderr:write()'\n";
assertEquals(expectedErrors, errors.toString());
// Evaluate script with redirection set
e.getContext().setReader(input);
e.getContext().setWriter(output);
e.getContext().setErrorWriter(errors);
e.eval(script);
final String expectedOutput = "string written using 'print'\n" + "string written using 'io.write()'\n"
+ "string written using 'io.stdout:write()'\n" + "string read using 'io.stdin:read(\"*l\")':abcdefg\n";
assertEquals(expectedOutput, output.toString());
final String expectedErrors = "string written using 'io.stderr:write()'\n";
assertEquals(expectedErrors, errors.toString());
// Evaluate script with redirection reset
output.reset();
errors.reset();
// e.getContext().setReader(null); // This will block if using actual STDIN
e.getContext().setWriter(null);
e.getContext().setErrorWriter(null);
e.eval(script);
assertEquals("", output.toString());
assertEquals("", errors.toString());
// Evaluate script with redirection reset
output.reset();
errors.reset();
// e.getContext().setReader(null); // This will block if using actual STDIN
e.getContext().setWriter(null);
e.getContext().setErrorWriter(null);
e.eval(script);
assertEquals("", output.toString());
assertEquals("", errors.toString());
}
public void testBindingJavaInt() throws ScriptException {
CompiledScript cs = ((Compilable)e).compile("y = x; return 'x '..type(x)..' '..tostring(x)\n");
b.put("x", 111);
assertEquals("x number 111", cs.eval(b));
assertEquals(111, b.get("y"));
CompiledScript cs = ((Compilable) e).compile("y = x; return 'x '..type(x)..' '..tostring(x)\n");
b.put("x", 111);
assertEquals("x number 111", cs.eval(b));
assertEquals(111, b.get("y"));
}
public void testBindingJavaDouble() throws ScriptException {
CompiledScript cs = ((Compilable)e).compile("y = x; return 'x '..type(x)..' '..tostring(x)\n");
b.put("x", 125.125);
assertEquals("x number 125.125", cs.eval(b));
assertEquals(125.125, b.get("y"));
CompiledScript cs = ((Compilable) e).compile("y = x; return 'x '..type(x)..' '..tostring(x)\n");
b.put("x", 125.125);
assertEquals("x number 125.125", cs.eval(b));
assertEquals(125.125, b.get("y"));
}
public void testBindingJavaString() throws ScriptException {
CompiledScript cs = ((Compilable)e).compile("y = x; return 'x '..type(x)..' '..tostring(x)\n");
b.put("x", "foo");
assertEquals("x string foo", cs.eval(b));
assertEquals("foo", b.get("y"));
CompiledScript cs = ((Compilable) e).compile("y = x; return 'x '..type(x)..' '..tostring(x)\n");
b.put("x", "foo");
assertEquals("x string foo", cs.eval(b));
assertEquals("foo", b.get("y"));
}
public void testBindingJavaObject() throws ScriptException {
CompiledScript cs = ((Compilable)e).compile("y = x; return 'x '..type(x)..' '..tostring(x)\n");
b.put("x", new SomeUserClass());
assertEquals("x userdata some-user-value", cs.eval(b));
assertEquals(SomeUserClass.class, b.get("y").getClass());
CompiledScript cs = ((Compilable) e).compile("y = x; return 'x '..type(x)..' '..tostring(x)\n");
b.put("x", new SomeUserClass());
assertEquals("x userdata some-user-value", cs.eval(b));
assertEquals(SomeUserClass.class, b.get("y").getClass());
}
public void testBindingJavaArray() throws ScriptException {
CompiledScript cs = ((Compilable)e).compile("y = x; return 'x '..type(x)..' '..#x..' '..x[1]..' '..x[2]\n");
b.put("x", new int[] { 777, 888 });
assertEquals("x userdata 2 777 888", cs.eval(b));
assertEquals(int[].class, b.get("y").getClass());
CompiledScript cs = ((Compilable) e)
.compile("y = x; return 'x '..type(x)..' '..#x..' '..x[1]..' '..x[2]\n");
b.put("x", new int[] { 777, 888 });
assertEquals("x userdata 2 777 888", cs.eval(b));
assertEquals(int[].class, b.get("y").getClass());
}
public void testBindingLuaFunction() throws ScriptException {
CompiledScript cs = ((Compilable)e).compile("y = function(x) return 678 + x end; return 'foo'");
assertEquals("foo", cs.eval(b).toString());
assertTrue(b.get("y") instanceof LuaFunction);
assertEquals(LuaValue.valueOf(801), ((LuaFunction) b.get("y")).call(LuaValue.valueOf(123)));
CompiledScript cs = ((Compilable) e).compile("y = function(x) return 678 + x end; return 'foo'");
assertEquals("foo", cs.eval(b).toString());
assertTrue(b.get("y") instanceof LuaFunction);
assertEquals(LuaValue.valueOf(801), ((LuaFunction) b.get("y")).call(LuaValue.valueOf(123)));
}
public void testUserClasses() throws ScriptException {
CompiledScript cs = ((Compilable)e).compile(
"x = x or luajava.newInstance('java.lang.String', 'test')\n" +
"return 'x ' .. type(x) .. ' ' .. tostring(x)\n");
assertEquals("x string test", cs.eval(b));
b.put("x", new SomeUserClass());
assertEquals("x userdata some-user-value", cs.eval(b));
}
public void testUserClasses() throws ScriptException {
CompiledScript cs = ((Compilable) e).compile("x = x or luajava.newInstance('java.lang.String', 'test')\n"
+ "return 'x ' .. type(x) .. ' ' .. tostring(x)\n");
assertEquals("x string test", cs.eval(b));
b.put("x", new SomeUserClass());
assertEquals("x userdata some-user-value", cs.eval(b));
}
public void testReturnMultipleValues() throws ScriptException {
CompiledScript cs = ((Compilable)e).compile("return 'foo', 'bar'\n");
Object o = cs.eval();
assertEquals(Object[].class, o.getClass());
Object[] array = (Object[]) o;
assertEquals(2, array.length);
assertEquals("foo", array[0]);
assertEquals("bar", array[1]);
CompiledScript cs = ((Compilable) e).compile("return 'foo', 'bar'\n");
Object o = cs.eval();
assertEquals(Object[].class, o.getClass());
Object[] array = (Object[]) o;
assertEquals(2, array.length);
assertEquals("foo", array[0]);
assertEquals("bar", array[1]);
}
}
public static class SomeUserClass {
public String toString() {
return "some-user-value";
}
}
public String toString() {
return "some-user-value";
}
}
public static class UserContextTest extends TestCase {
protected ScriptEngine e;
protected Bindings b;
public static class UserContextTest extends TestCase {
protected ScriptEngine e;
protected Bindings b;
protected ScriptContext c;
public void setUp() {
this.e = new ScriptEngineManager().getEngineByName("luaj");
this.e = new ScriptEngineManager().getEngineByName("luaj");
this.c = new LuajContext();
this.b = c.getBindings(ScriptContext.ENGINE_SCOPE);
}
public void testUncompiledScript() throws ScriptException {
b.put("x", 144);
assertEquals(12, e.eval("z = math.sqrt(x); return z", b));
assertEquals(12, b.get("z"));
assertEquals(null, e.getBindings(ScriptContext.ENGINE_SCOPE).get("z"));
assertEquals(null, e.getBindings(ScriptContext.GLOBAL_SCOPE).get("z"));
b.put("x", 144);
assertEquals(12, e.eval("z = math.sqrt(x); return z", b));
assertEquals(12, b.get("z"));
assertEquals(null, e.getBindings(ScriptContext.ENGINE_SCOPE).get("z"));
assertEquals(null, e.getBindings(ScriptContext.GLOBAL_SCOPE).get("z"));
b.put("x", 25);
assertEquals(5, e.eval("z = math.sqrt(x); return z", c));
assertEquals(5, b.get("z"));
assertEquals(null, e.getBindings(ScriptContext.ENGINE_SCOPE).get("z"));
assertEquals(null, e.getBindings(ScriptContext.GLOBAL_SCOPE).get("z"));
b.put("x", 25);
assertEquals(5, e.eval("z = math.sqrt(x); return z", c));
assertEquals(5, b.get("z"));
assertEquals(null, e.getBindings(ScriptContext.ENGINE_SCOPE).get("z"));
assertEquals(null, e.getBindings(ScriptContext.GLOBAL_SCOPE).get("z"));
}
public void testCompiledScript() throws ScriptException {
CompiledScript cs = ((Compilable)e).compile("z = math.sqrt(x); return z");
b.put("x", 144);
assertEquals(12, cs.eval(b));
assertEquals(12, b.get("z"));
b.put("x", 25);
assertEquals(5, cs.eval(c));
assertEquals(5, b.get("z"));
public void testCompiledScript() throws ScriptException {
CompiledScript cs = ((Compilable) e).compile("z = math.sqrt(x); return z");
b.put("x", 144);
assertEquals(12, cs.eval(b));
assertEquals(12, b.get("z"));
b.put("x", 25);
assertEquals(5, cs.eval(c));
assertEquals(5, b.get("z"));
}
}
public static class WriterTest extends TestCase {
public static class WriterTest extends TestCase {
protected ScriptEngine e;
protected Bindings b;
protected Bindings b;
public void setUp() {
this.e = new ScriptEngineManager().getEngineByName("luaj");
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();
}
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();
}
}
}