diff --git a/.classpath b/.classpath deleted file mode 100644 index eded28b8..00000000 --- a/.classpath +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - - - - - - - - - - diff --git a/.gitignore b/.gitignore index d7642856..18d2ca6c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,15 +1,4 @@ -bin/ target/ -build/ -lib/ -jit/ -*.ser -*.gz -*.jar -*.lua -*.out -*.tar -*.txt -*.zip -docs -*.0 +.classpath +.project +.settings/ diff --git a/.ide/cleanup.xml b/.ide/cleanup.xml new file mode 100644 index 00000000..c7efe5ee --- /dev/null +++ b/.ide/cleanup.xml @@ -0,0 +1,138 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.ide/formatter.xml b/.ide/formatter.xml new file mode 100644 index 00000000..55933d98 --- /dev/null +++ b/.ide/formatter.xml @@ -0,0 +1,390 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.project b/.project deleted file mode 100644 index 15180d11..00000000 --- a/.project +++ /dev/null @@ -1,17 +0,0 @@ - - - luaj-vm - - - - - - org.eclipse.jdt.core.javabuilder - - - - - - org.eclipse.jdt.core.javanature - - diff --git a/README.md b/README.md index 30f17dbd..76508025 100644 --- a/README.md +++ b/README.md @@ -858,37 +858,30 @@ An example skelton maven pom file for a skeleton project is in

Building the jars

-An ant file is included in the root directory which builds the libraries by default. +Build the jars with maven. +
+	mvn clean verify
+

-Other targets exist for creating distribution file an measuring code coverage of unit tests.

Unit tests

-The main luaj JUnit tests are organized into a JUnit 3 suite: -

-	test/junit/org/luaj/vm2/AllTests.lua
-
+All unit tests are executed during the build.

-Unit test scripts can be found in these locations +Test scripts can be found in these locations

-	test/lua/*.lua
-	test/lua/errors/*.lua
-	test/lua/perf/*.lua
-	test/lua/luaj3.0.2-tests.zip
+	luaj-test/src/test/resources
 
+Executon is included in the build of luaj-test.

Code coverage

-A build script for running unit tests and producing code coverage statistics is in -

-	build-coverage.xml
-
- -It relies on the cobertura code coverage library. +The maven build creates the coverage report in the luaj-test/target/site folder +during the verify phase.

8 - Downloads

diff --git a/build-app.xml b/build-app.xml deleted file mode 100644 index a3985c9d..00000000 --- a/build-app.xml +++ /dev/null @@ -1,108 +0,0 @@ - - - - - - - - - - - - - - - - - - - ------ @{cmd} - - - - - - - - - - - - - =========== @{srcdir}/@{luaprog} ============= - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/build-applet.xml b/build-applet.xml deleted file mode 100644 index d27b4420..00000000 --- a/build-applet.xml +++ /dev/null @@ -1,116 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -injars ${build.dir}/${script.name}-unobfuscated.jar - -outjars ${build.dir}/${script.name}.jar - -libraryjars ${java.home}/lib/rt.jar - -overloadaggressively - -repackageclasses '' - -allowaccessmodification - -printmapping ${build.dir}/mapping.txt - - -keep public class * extends java.applet.Applet - - -target 1.4 - - - - - - - - - - - Luaj Sample Applet - -

Luaj Sample Applet

- Requires browser that supports applets. - ${script.name} - - - - - - -
-
- - - - - - - - - - - - -
diff --git a/build-coverage.xml b/build-coverage.xml deleted file mode 100644 index 8a491f8c..00000000 --- a/build-coverage.xml +++ /dev/null @@ -1,119 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/build-libs.xml b/build-libs.xml deleted file mode 100644 index 872c5bb8..00000000 --- a/build-libs.xml +++ /dev/null @@ -1,56 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/build-maven.xml b/build-maven.xml deleted file mode 100644 index 33e2211d..00000000 --- a/build-maven.xml +++ /dev/null @@ -1,176 +0,0 @@ - - - - - - - - - - - 4.0.0 - org.luaj - luaj-]]>@{platform} - ]]>${version}@{snapshot} - jar - luaj-]]>@{platform} - Luaj ]]>${version}@{platform} - http://sourceforge.net/projects/luaj/ - - - MIT License - http://luaj.sourceforge.net/license.txt - repo - - - - - jrosebor - James Roseborough - jim.roseborough@luaj.org - -8 - - - - ifarmer - Ian Farmer - ian.farmer@luaj.org - -8 - - - - - http://luaj.cvs.sourceforge.net/viewvc/luaj/luaj-vm/ - - -]]> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Luaj API]]> - Copyright © 2007-2015 Luaj.org. All Rights Reserved.]]> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Usage: ant [-Dversion=${version}] -f build-maven.xml [install | shapshot | deploy] - - diff --git a/build-midlet.xml b/build-midlet.xml deleted file mode 100644 index 89457961..00000000 --- a/build-midlet.xml +++ /dev/null @@ -1,113 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -injars build/sample-plain.jar - -outjars build/sample.jar - -libraryjars lib/midpapi20.jar - -libraryjars lib/cldcapi11.jar - -overloadaggressively - -repackageclasses '' - -microedition - - -keep public class SampleMIDlet - -keep public class * extends org.luaj.vm2.LuaValue - - - - - - Jar file length is ${sample.jar.length} - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/build-perf.xml b/build-perf.xml deleted file mode 100644 index 63007823..00000000 --- a/build-perf.xml +++ /dev/null @@ -1,68 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ------ @{program} @{luaprog} - - - - - - - - - - - - =========== @{luaprog} ============= - - - - - - - - - - - - - - - - diff --git a/build.xml b/build.xml deleted file mode 100644 index e0ea7f0d..00000000 --- a/build.xml +++ /dev/null @@ -1,212 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Luaj API]]> - Copyright © 2007-2015 Luaj.org. All Rights Reserved.]]> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/luaj-core/pom.xml b/luaj-core/pom.xml new file mode 100644 index 00000000..021158cd --- /dev/null +++ b/luaj-core/pom.xml @@ -0,0 +1,25 @@ + + 4.0.0 + + + org.luaj + luaj-parent + 3.0-SNAPSHOT + + + luaj-core + + luaj-core + Core code for LuaJ + + + + org.junit.jupiter + junit-jupiter + test + + + + diff --git a/src/core/org/luaj/vm2/Buffer.java b/luaj-core/src/main/java/org/luaj/vm2/Buffer.java similarity index 66% rename from src/core/org/luaj/vm2/Buffer.java rename to luaj-core/src/main/java/org/luaj/vm2/Buffer.java index 0a1117c4..ba393bcb 100644 --- a/src/core/org/luaj/vm2/Buffer.java +++ b/luaj-core/src/main/java/org/luaj/vm2/Buffer.java @@ -10,7 +10,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,61 +21,64 @@ ******************************************************************************/ package org.luaj.vm2; - /** - * String buffer for use in string library methods, optimized for production - * of StrValue instances. + * String buffer for use in string library methods, optimized for production of + * StrValue instances. *

- * The buffer can begin initially as a wrapped {@link LuaValue} - * and only when concatenation actually occurs are the bytes first copied. - *

- * To convert back to a {@link LuaValue} again, - * the function {@link Buffer#value()} is used. + * The buffer can begin initially as a wrapped {@link LuaValue} and only when + * concatenation actually occurs are the bytes first copied. + *

+ * To convert back to a {@link LuaValue} again, the function + * {@link Buffer#value()} is used. + * * @see LuaValue * @see LuaValue#buffer() * @see LuaString */ public final class Buffer { - + /** Default capacity for a buffer: 64 */ private static final int DEFAULT_CAPACITY = 64; - + /** Shared static array with no bytes */ private static final byte[] NOBYTES = {}; /** Bytes in this buffer */ private byte[] bytes; - + /** Length of this buffer */ private int length; - + /** Offset into the byte array */ private int offset; - + /** Value of this buffer, when not represented in bytes */ private LuaValue value; - + /** * Create buffer with default capacity + * * @see #DEFAULT_CAPACITY */ public Buffer() { this(DEFAULT_CAPACITY); } - + /** * Create buffer with specified initial capacity + * * @param initialCapacity the initial capacity */ - public Buffer( int initialCapacity ) { - bytes = new byte[ initialCapacity ]; + public Buffer(int initialCapacity) { + bytes = new byte[initialCapacity]; length = 0; offset = 0; value = null; } - + /** * Create buffer with specified initial value + * * @param value the initial value */ public Buffer(LuaValue value) { @@ -84,16 +87,18 @@ public final class Buffer { this.value = value; } - /** + /** * Get buffer contents as a {@link LuaValue} + * * @return value as a {@link LuaValue}, converting as necessary */ public LuaValue value() { return value != null? value: this.tostring(); } - /** + /** * Set buffer contents as a {@link LuaValue} + * * @param value value to set */ public Buffer setvalue(LuaValue value) { @@ -102,145 +107,171 @@ public final class Buffer { this.value = value; return this; } - - /** + + /** * Convert the buffer to a {@link LuaString} + * * @return the value as a {@link LuaString} */ - public final LuaString tostring() { - realloc( length, 0 ); - return LuaString.valueOf( bytes, offset, length ); + public LuaString tostring() { + realloc(length, 0); + return LuaString.valueOf(bytes, offset, length); } - - /** + + /** * Convert the buffer to a Java String + * * @return the value as a Java String */ public String tojstring() { return value().tojstring(); } - - /** + + /** * Convert the buffer to a Java String + * * @return the value as a Java String */ + @Override public String toString() { return tojstring(); } - /** + /** * Append a single byte to the buffer. + * * @return {@code this} to allow call chaining */ - public final Buffer append( byte b ) { - makeroom( 0, 1 ); - bytes[ offset + length++ ] = b; + public Buffer append(byte b) { + makeroom(0, 1); + bytes[offset+length++] = b; return this; } - /** + /** * Append a {@link LuaValue} to the buffer. + * * @return {@code this} to allow call chaining */ - public final Buffer append( LuaValue val ) { - append( val.strvalue() ); + public Buffer append(LuaValue val) { + append(val.strvalue()); return this; } - - /** + + /** * Append a {@link LuaString} to the buffer. + * * @return {@code this} to allow call chaining */ - public final Buffer append( LuaString str ) { + public Buffer append(LuaString str) { final int n = str.m_length; - makeroom( 0, n ); - str.copyInto( 0, bytes, offset + length, n ); + makeroom(0, n); + str.copyInto(0, bytes, offset+length, n); length += n; return this; } - - /** - * Append a Java String to the buffer. - * The Java string will be converted to bytes using the UTF8 encoding. + + /** + * Append a Java String to the buffer. The Java string will be converted to + * bytes using the UTF8 encoding. + * * @return {@code this} to allow call chaining * @see LuaString#encodeToUtf8(char[], int, byte[], int) */ - public final Buffer append( String str ) { + public Buffer append(String str) { char[] c = str.toCharArray(); - final int n = LuaString.lengthAsUtf8( c ); - makeroom( 0, n ); - LuaString.encodeToUtf8( c, c.length, bytes, offset + length ); + final int n = LuaString.lengthAsUtf8(c); + makeroom(0, n); + LuaString.encodeToUtf8(c, c.length, bytes, offset+length); length += n; return this; } - /** Concatenate this buffer onto a {@link LuaValue} - * @param lhs the left-hand-side value onto which we are concatenating {@code this} + /** + * Concatenate this buffer onto a {@link LuaValue} + * + * @param lhs the left-hand-side value onto which we are concatenating + * {@code this} * @return {@link Buffer} for use in call chaining. */ public Buffer concatTo(LuaValue lhs) { return setvalue(lhs.concat(value())); } - /** Concatenate this buffer onto a {@link LuaString} - * @param lhs the left-hand-side value onto which we are concatenating {@code this} + /** + * Concatenate this buffer onto a {@link LuaString} + * + * @param lhs the left-hand-side value onto which we are concatenating + * {@code this} * @return {@link Buffer} for use in call chaining. */ public Buffer concatTo(LuaString lhs) { - return value!=null&&!value.isstring()? setvalue(lhs.concat(value)): prepend(lhs); + return value != null && !value.isstring()? setvalue(lhs.concat(value)): prepend(lhs); } - /** Concatenate this buffer onto a {@link LuaNumber} + /** + * Concatenate this buffer onto a {@link LuaNumber} *

- * The {@link LuaNumber} will be converted to a string before concatenating. - * @param lhs the left-hand-side value onto which we are concatenating {@code this} + * The {@link LuaNumber} will be converted to a string before concatenating. + * + * @param lhs the left-hand-side value onto which we are concatenating + * {@code this} * @return {@link Buffer} for use in call chaining. */ public Buffer concatTo(LuaNumber lhs) { - return value!=null&&!value.isstring()? setvalue(lhs.concat(value)): prepend(lhs.strvalue()); + return value != null && !value.isstring()? setvalue(lhs.concat(value)): prepend(lhs.strvalue()); } - /** Concatenate bytes from a {@link LuaString} onto the front of this buffer - * @param s the left-hand-side value which we will concatenate onto the front of {@code this} + /** + * Concatenate bytes from a {@link LuaString} onto the front of this buffer + * + * @param s the left-hand-side value which we will concatenate onto the + * front of {@code this} * @return {@link Buffer} for use in call chaining. */ public Buffer prepend(LuaString s) { int n = s.m_length; - makeroom( n, 0 ); - System.arraycopy( s.m_bytes, s.m_offset, bytes, offset-n, n ); + makeroom(n, 0); + System.arraycopy(s.m_bytes, s.m_offset, bytes, offset-n, n); offset -= n; length += n; value = null; return this; } - /** Ensure there is enough room before and after the bytes. - * @param nbefore number of unused bytes which must precede the data after this completes - * @param nafter number of unused bytes which must follow the data after this completes + /** + * Ensure there is enough room before and after the bytes. + * + * @param nbefore number of unused bytes which must precede the data after + * this completes + * @param nafter number of unused bytes which must follow the data after + * this completes */ - public final void makeroom( int nbefore, int nafter ) { - if ( value != null ) { + public void makeroom(int nbefore, int nafter) { + if (value != null) { LuaString s = value.strvalue(); value = null; length = s.m_length; offset = nbefore; bytes = new byte[nbefore+length+nafter]; System.arraycopy(s.m_bytes, s.m_offset, bytes, offset, length); - } else if ( offset+length+nafter > bytes.length || offset bytes.length || offset < nbefore) { int n = nbefore+length+nafter; - int m = n<32? 32: n - * - *

Constructing and Initializing Instances

- * Typically, this is constructed indirectly by a call to - * {@link org.luaj.vm2.lib.jse.JsePlatform#standardGlobals()} or - * {@link org.luaj.vm2.lib.jme.JmePlatform#standardGlobals()}, - * and then used to load lua scripts for execution as in the following example. - *
 {@code
- * Globals globals = JsePlatform.standardGlobals();
- * globals.load( new StringReader("print 'hello'"), "main.lua" ).call(); 
- * } 
+ * + *

Constructing and Initializing Instances

Typically, this is + * constructed indirectly by a call to + * {@link org.luaj.vm2.lib.jse.JsePlatform#standardGlobals()} or + * {@link org.luaj.vm2.lib.jme.JmePlatform#standardGlobals()}, and then used to + * load lua scripts for execution as in the following example. + * + *
+ * {
+ * 	@code
+ * 	Globals globals = JsePlatform.standardGlobals();
+ * 	globals.load(new StringReader("print 'hello'"), "main.lua").call();
+ * }
+ * 
+ * * The creates a complete global environment with the standard libraries loaded. *

- * For specialized circumstances, the Globals may be constructed directly and loaded - * with only those libraries that are needed, for example. - *

 {@code
- * Globals globals = new Globals();
- * globals.load( new BaseLib() ); 
- * } 
- * - *

Loading and Executing Lua Code

- * Globals contains convenience functions to load and execute lua source code given a Reader. - * A simple example is: - *
 {@code
- * globals.load( new StringReader("print 'hello'"), "main.lua" ).call(); 
- * } 
- * - *

Fine-Grained Control of Compiling and Loading Lua

- * Executable LuaFunctions are created from lua code in several steps + * For specialized circumstances, the Globals may be constructed directly and + * loaded with only those libraries that are needed, for example. + * + *
+ * {
+ * 	@code
+ * 	Globals globals = new Globals();
+ * 	globals.load(new BaseLib());
+ * }
+ * 
+ * + *

Loading and Executing Lua Code

Globals contains convenience + * functions to load and execute lua source code given a Reader. A simple + * example is: + * + *
+ *  {@code
+ * globals.load( new StringReader("print 'hello'"), "main.lua" ).call();
+ * }
+ * 
+ * + *

Fine-Grained Control of Compiling and Loading Lua

Executable + * LuaFunctions are created from lua code in several steps * *

- * There are alternate flows when the direct lua-to-Java bytecode compiling {@link org.luaj.vm2.luajc.LuaJC} is used. + * There are alternate flows when the direct lua-to-Java bytecode compiling + * {@link org.luaj.vm2.luajc.LuaJC} is used. *

- * - *

Java Field

- * Certain public fields are provided that contain the current values of important global state: + * + *

Java Field

Certain public fields are provided that contain the + * current values of important global state: * - * - *

Lua Environment Variables

- * When using {@link org.luaj.vm2.lib.jse.JsePlatform} or {@link org.luaj.vm2.lib.jme.JmePlatform}, - * these environment variables are created within the Globals. + * + *

Lua Environment Variables

When using + * {@link org.luaj.vm2.lib.jse.JsePlatform} or + * {@link org.luaj.vm2.lib.jme.JmePlatform}, these environment variables are + * created within the Globals. * - * - *

Use in Multithreaded Environments

- * In a multi-threaded server environment, each server thread should create one Globals instance, - * which will be logically distinct and not interfere with each other, but share certain - * static immutable resources such as class data and string data. + * + *

Use in Multithreaded Environments

In a multi-threaded server + * environment, each server thread should create one Globals instance, which + * will be logically distinct and not interfere with each other, but share + * certain static immutable resources such as class data and string data. *

- * + * * @see org.luaj.vm2.lib.jse.JsePlatform * @see org.luaj.vm2.lib.jme.JmePlatform * @see LuaValue @@ -115,7 +136,7 @@ import org.luaj.vm2.lib.ResourceFinder; public class Globals extends LuaTable { /** The current default input stream. */ - public InputStream STDIN = null; + public InputStream STDIN = null; /** The current default output stream. */ public PrintStream STDOUT = System.out; @@ -125,28 +146,42 @@ public class Globals extends LuaTable { /** The installed ResourceFinder for looking files by name. */ public ResourceFinder finder; - - /** The currently running thread. Should not be changed by non-library code. */ + + /** + * The currently running thread. Should not be changed by non-library code. + */ public LuaThread running = new LuaThread(this); /** The BaseLib instance loaded into this Globals */ public BaseLib baselib; - + /** The PackageLib instance loaded into this Globals */ public PackageLib package_; - - /** The DebugLib instance loaded into this Globals, or null if debugging is not enabled */ + + /** + * The DebugLib instance loaded into this Globals, or null if debugging is + * not enabled + */ public DebugLib debuglib; - /** Interface for module that converts a Prototype into a LuaFunction with an environment. */ + /** + * Interface for module that converts a Prototype into a LuaFunction with an + * environment. + */ public interface Loader { - /** Convert the prototype into a LuaFunction with the supplied environment. */ + /** + * Convert the prototype into a LuaFunction with the supplied + * environment. + */ LuaFunction load(Prototype prototype, String chunkname, LuaValue env) throws IOException; } /** Interface for module that converts lua source text into a prototype. */ public interface Compiler { - /** Compile lua source into a Prototype. The InputStream is assumed to be in UTF-8. */ + /** + * Compile lua source into a Prototype. The InputStream is assumed to be + * in UTF-8. + */ Prototype compile(InputStream stream, String chunkname) throws IOException; } @@ -155,100 +190,143 @@ public class Globals extends LuaTable { /** Load the supplied input stream into a prototype. */ Prototype undump(InputStream stream, String chunkname) throws IOException; } - - /** Check that this object is a Globals object, and return it, otherwise throw an error. */ + + /** + * Check that this object is a Globals object, and return it, otherwise + * throw an error. + */ + @Override public Globals checkglobals() { return this; } - - /** The installed loader. - * @see Loader */ + + /** + * The installed loader. + * + * @see Loader + */ public Loader loader; - /** The installed compiler. - * @see Compiler */ + /** + * The installed compiler. + * + * @see Compiler + */ public Compiler compiler; - /** The installed undumper. - * @see Undumper */ + /** + * The installed undumper. + * + * @see Undumper + */ public Undumper undumper; - /** Convenience function for loading a file that is either binary lua or lua source. + /** + * Convenience function for loading a file that is either binary lua or lua + * source. + * * @param filename Name of the file to load. * @return LuaValue that can be call()'ed or invoke()'ed. * @throws LuaError if the file could not be loaded. */ public LuaValue loadfile(String filename) { try { - return load(finder.findResource(filename), "@"+filename, "bt", this); + return load(finder.findResource(filename), "@" + filename, "bt", this); } catch (Exception e) { - return error("load "+filename+": "+e); + return error("load " + filename + ": " + e); } } - /** Convenience function to load a string value as a script. Must be lua source. - * @param script Contents of a lua script, such as "print 'hello, world.'" + /** + * Convenience function to load a string value as a script. Must be lua + * source. + * + * @param script Contents of a lua script, such as "print 'hello, + * world.'" * @param chunkname Name that will be used within the chunk as the source. - * @return LuaValue that may be executed via .call(), .invoke(), or .method() calls. + * @return LuaValue that may be executed via .call(), .invoke(), or + * .method() calls. * @throws LuaError if the script could not be compiled. */ public LuaValue load(String script, String chunkname) { return load(new StrReader(script), chunkname); } - - /** Convenience function to load a string value as a script. Must be lua source. + + /** + * Convenience function to load a string value as a script. Must be lua + * source. + * * @param script Contents of a lua script, such as "print 'hello, world.'" - * @return LuaValue that may be executed via .call(), .invoke(), or .method() calls. + * @return LuaValue that may be executed via .call(), .invoke(), or + * .method() calls. * @throws LuaError if the script could not be compiled. */ public LuaValue load(String script) { return load(new StrReader(script), script); } - /** Convenience function to load a string value as a script with a custom environment. - * Must be lua source. - * @param script Contents of a lua script, such as "print 'hello, world.'" - * @param chunkname Name that will be used within the chunk as the source. - * @param environment LuaTable to be used as the environment for the loaded function. - * @return LuaValue that may be executed via .call(), .invoke(), or .method() calls. + /** + * Convenience function to load a string value as a script with a custom + * environment. Must be lua source. + * + * @param script Contents of a lua script, such as "print 'hello, + * world.'" + * @param chunkname Name that will be used within the chunk as the source. + * @param environment LuaTable to be used as the environment for the loaded + * function. + * @return LuaValue that may be executed via .call(), .invoke(), or + * .method() calls. * @throws LuaError if the script could not be compiled. */ public LuaValue load(String script, String chunkname, LuaTable environment) { return load(new StrReader(script), chunkname, environment); } - /** Load the content form a reader as a text file. Must be lua source. - * The source is converted to UTF-8, so any characters appearing in quoted literals - * above the range 128 will be converted into multiple bytes. - * @param reader Reader containing text of a lua script, such as "print 'hello, world.'" + /** + * Load the content form a reader as a text file. Must be lua source. The + * source is converted to UTF-8, so any characters appearing in quoted + * literals above the range 128 will be converted into multiple bytes. + * + * @param reader Reader containing text of a lua script, such as "print + * 'hello, world.'" * @param chunkname Name that will be used within the chunk as the source. - * @return LuaValue that may be executed via .call(), .invoke(), or .method() calls. + * @return LuaValue that may be executed via .call(), .invoke(), or + * .method() calls. * @throws LuaError if the script could not be compiled. - */ + */ public LuaValue load(Reader reader, String chunkname) { return load(new UTF8Stream(reader), chunkname, "t", this); } - /** Load the content form a reader as a text file, supplying a custom environment. - * Must be lua source. The source is converted to UTF-8, so any characters - * appearing in quoted literals above the range 128 will be converted into - * multiple bytes. - * @param reader Reader containing text of a lua script, such as "print 'hello, world.'" - * @param chunkname Name that will be used within the chunk as the source. - * @param environment LuaTable to be used as the environment for the loaded function. - * @return LuaValue that may be executed via .call(), .invoke(), or .method() calls. + /** + * Load the content form a reader as a text file, supplying a custom + * environment. Must be lua source. The source is converted to UTF-8, so any + * characters appearing in quoted literals above the range 128 will be + * converted into multiple bytes. + * + * @param reader Reader containing text of a lua script, such as "print + * 'hello, world.'" + * @param chunkname Name that will be used within the chunk as the source. + * @param environment LuaTable to be used as the environment for the loaded + * function. + * @return LuaValue that may be executed via .call(), .invoke(), or + * .method() calls. * @throws LuaError if the script could not be compiled. - */ + */ public LuaValue load(Reader reader, String chunkname, LuaTable environment) { return load(new UTF8Stream(reader), chunkname, "t", environment); - } + } - /** Load the content form an input stream as a binary chunk or text file. - * @param is InputStream containing a lua script or compiled lua" - * @param chunkname Name that will be used within the chunk as the source. - * @param mode String containing 'b' or 't' or both to control loading as binary or text or either. - * @param environment LuaTable to be used as the environment for the loaded function. - * */ + /** + * Load the content form an input stream as a binary chunk or text file. + * + * @param is InputStream containing a lua script or compiled lua" + * @param chunkname Name that will be used within the chunk as the source. + * @param mode String containing 'b' or 't' or both to control + * loading as binary or text or either. + * @param environment LuaTable to be used as the environment for the loaded + * function. + */ public LuaValue load(InputStream is, String chunkname, String mode, LuaValue environment) { try { Prototype p = loadPrototype(is, chunkname, mode); @@ -256,16 +334,20 @@ public class Globals extends LuaTable { } catch (LuaError l) { throw l; } catch (Exception e) { - return error("load "+chunkname+": "+e); + return error("load " + chunkname + ": " + e); } } - /** Load lua source or lua binary from an input stream into a Prototype. - * The InputStream is either a binary lua chunk starting with the lua binary chunk signature, - * or a text input file. If it is a text input file, it is interpreted as a UTF-8 byte sequence. - * @param is Input stream containing a lua script or compiled lua" + /** + * Load lua source or lua binary from an input stream into a Prototype. The + * InputStream is either a binary lua chunk starting with the lua binary + * chunk signature, or a text input file. If it is a text input file, it is + * interpreted as a UTF-8 byte sequence. + * + * @param is Input stream containing a lua script or compiled lua" * @param chunkname Name that will be used within the chunk as the source. - * @param mode String containing 'b' or 't' or both to control loading as binary or text or either. + * @param mode String containing 'b' or 't' or both to control loading + * as binary or text or either. */ public Prototype loadPrototype(InputStream is, String chunkname, String mode) throws IOException { if (mode.indexOf('b') >= 0) { @@ -282,21 +364,25 @@ public class Globals extends LuaTable { if (mode.indexOf('t') >= 0) { return compilePrototype(is, chunkname); } - error("Failed to load prototype "+chunkname+" using mode '"+mode+"'"); + error("Failed to load prototype " + chunkname + " using mode '" + mode + "'"); return null; } - - /** Compile lua source from a Reader into a Prototype. The characters in the reader - * are converted to bytes using the UTF-8 encoding, so a string literal containing - * characters with codepoints 128 or above will be converted into multiple bytes. + + /** + * Compile lua source from a Reader into a Prototype. The characters in the + * reader are converted to bytes using the UTF-8 encoding, so a string + * literal containing characters with codepoints 128 or above will be + * converted into multiple bytes. */ public Prototype compilePrototype(Reader reader, String chunkname) throws IOException { return compilePrototype(new UTF8Stream(reader), chunkname); } - - /** Compile lua source from an InputStream into a Prototype. - * The input is assumed to be UTf-8, but since bytes in the range 128-255 are passed along as - * literal bytes, any ASCII-compatible encoding such as ISO 8859-1 may also be used. + + /** + * Compile lua source from an InputStream into a Prototype. The input is + * assumed to be UTf-8, but since bytes in the range 128-255 are passed + * along as literal bytes, any ASCII-compatible encoding such as ISO 8859-1 + * may also be used. */ public Prototype compilePrototype(InputStream stream, String chunkname) throws IOException { if (compiler == null) @@ -304,9 +390,13 @@ public class Globals extends LuaTable { return compiler.compile(stream, chunkname); } - /** Function which yields the current thread. - * @param args Arguments to supply as return values in the resume function of the resuming thread. - * @return Values supplied as arguments to the resume() call that reactivates this thread. + /** + * Function which yields the current thread. + * + * @param args Arguments to supply as return values in the resume function + * of the resuming thread. + * @return Values supplied as arguments to the resume() call that + * reactivates this thread. */ public Varargs yield(Varargs args) { if (running == null || running.isMainThread()) @@ -318,23 +408,30 @@ public class Globals extends LuaTable { /** Reader implementation to read chars from a String in JME or JSE. */ static class StrReader extends Reader { final String s; - int i = 0; - final int n; + int i = 0; + final int n; + StrReader(String s) { this.s = s; n = s.length(); } + + @Override public void close() throws IOException { i = n; } + + @Override public int read() throws IOException { - return i < n ? s.charAt(i++) : -1; + return i < n? s.charAt(i++): -1; } + + @Override public int read(char[] cbuf, int off, int len) throws IOException { int j = 0; for (; j < len && i < n; ++j, ++i) cbuf[off+j] = s.charAt(i); - return j > 0 || len == 0 ? j : -1; + return j > 0 || len == 0? j: -1; } } @@ -343,49 +440,67 @@ public class Globals extends LuaTable { */ abstract static class AbstractBufferedStream extends InputStream { protected byte[] b; - protected int i = 0, j = 0; + protected int i = 0, j = 0; + protected AbstractBufferedStream(int buflen) { this.b = new byte[buflen]; } + abstract protected int avail() throws IOException; + + @Override public int read() throws IOException { int a = avail(); - return (a <= 0 ? -1 : 0xff & b[i++]); + return a <= 0? -1: 0xff & b[i++]; } + + @Override public int read(byte[] b) throws IOException { return read(b, 0, b.length); } + + @Override public int read(byte[] b, int i0, int n) throws IOException { int a = avail(); - if (a <= 0) return -1; + if (a <= 0) + return -1; final int n_read = Math.min(a, n); - System.arraycopy(this.b, i, b, i0, n_read); + System.arraycopy(this.b, i, b, i0, n_read); i += n_read; return n_read; } + + @Override public long skip(long n) throws IOException { - final long k = Math.min(n, j - i); + final long k = Math.min(n, j-i); i += k; return k; - } + } + + @Override public int available() throws IOException { - return j - i; + return j-i; } } - /** Simple converter from Reader to InputStream using UTF8 encoding that will work - * on both JME and JSE. - * This class may be moved to its own package in the future. + /** + * Simple converter from Reader to InputStream using UTF8 encoding that will + * work on both JME and JSE. This class may be moved to its own package in + * the future. */ static class UTF8Stream extends AbstractBufferedStream { private final char[] c = new char[32]; private final Reader r; + UTF8Stream(Reader r) { super(96); this.r = r; } + + @Override protected int avail() throws IOException { - if (i < j) return j - i; + if (i < j) + return j-i; int n = r.read(c); if (n < 0) return -1; @@ -399,31 +514,40 @@ public class Globals extends LuaTable { j = LuaString.encodeToUtf8(c, n, b, i = 0); return j; } + + @Override public void close() throws IOException { r.close(); } } - - /** Simple buffered InputStream that supports mark. - * Used to examine an InputStream for a 4-byte binary lua signature, - * and fall back to text input when the signature is not found, - * as well as speed up normal compilation and reading of lua scripts. - * This class may be moved to its own package in the future. + + /** + * Simple buffered InputStream that supports mark. Used to examine an + * InputStream for a 4-byte binary lua signature, and fall back to text + * input when the signature is not found, as well as speed up normal + * compilation and reading of lua scripts. This class may be moved to its + * own package in the future. */ static class BufferedStream extends AbstractBufferedStream { private final InputStream s; + public BufferedStream(InputStream s) { this(128, s); } + BufferedStream(int buflen, InputStream s) { super(buflen); this.s = s; } + + @Override protected int avail() throws IOException { - if (i < j) return j - i; - if (j >= b.length) i = j = 0; + if (i < j) + return j-i; + if (j >= b.length) + i = j = 0; // leave previous bytes in place to implement mark()/reset(). - int n = s.read(b, j, b.length - j); + int n = s.read(b, j, b.length-j); if (n < 0) return -1; if (n == 0) { @@ -436,21 +560,29 @@ public class Globals extends LuaTable { j += n; return n; } + + @Override public void close() throws IOException { s.close(); } + + @Override public synchronized void mark(int n) { if (i > 0 || n > b.length) { - byte[] dest = n > b.length ? new byte[n] : b; - System.arraycopy(b, i, dest, 0, j - i); + byte[] dest = n > b.length? new byte[n]: b; + System.arraycopy(b, i, dest, 0, j-i); j -= i; i = 0; b = dest; } } + + @Override public boolean markSupported() { return true; } + + @Override public synchronized void reset() throws IOException { i = 0; } diff --git a/src/core/org/luaj/vm2/LoadState.java b/luaj-core/src/main/java/org/luaj/vm2/LoadState.java similarity index 51% rename from src/core/org/luaj/vm2/LoadState.java rename to luaj-core/src/main/java/org/luaj/vm2/LoadState.java index 8d71a74a..3dd25cff 100644 --- a/src/core/org/luaj/vm2/LoadState.java +++ b/luaj-core/src/main/java/org/luaj/vm2/LoadState.java @@ -10,7 +10,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. -* +* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,116 +25,141 @@ import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; - /** -* Class to undump compiled lua bytecode into a {@link Prototype} instances. -*

-* The {@link LoadState} class provides the default {@link Globals.Undumper} -* which is used to undump a string of bytes that represent a lua binary file -* using either the C-based lua compiler, or luaj's -* {@link org.luaj.vm2.compiler.LuaC} compiler. -*

-* The canonical method to load and execute code is done -* indirectly using the Globals: -*

 {@code
-* Globals globals = JsePlatform.standardGlobals();
-* LuaValue chunk = globasl.load("print('hello, world')", "main.lua");
-* chunk.call();
-* } 
-* This should work regardless of which {@link Globals.Compiler} or {@link Globals.Undumper} -* have been installed. -*

-* By default, when using {@link org.luaj.vm2.lib.jse.JsePlatform} or -* {@link org.luaj.vm2.lib.jme.JmePlatform} -* to construct globals, the {@link LoadState} default undumper is installed -* as the default {@link Globals.Undumper}. -*

-* -* A lua binary file is created via the {@link org.luaj.vm2.compiler.DumpState} class -: -*

 {@code
-* Globals globals = JsePlatform.standardGlobals();
-* Prototype p = globals.compilePrototype(new StringReader("print('hello, world')"), "main.lua");
-* ByteArrayOutputStream o = new ByteArrayOutputStream();
-* org.luaj.vm2.compiler.DumpState.dump(p, o, false);
-* byte[] lua_binary_file_bytes = o.toByteArray();
-* } 
-* -* The {@link LoadState}'s default undumper {@link #instance} -* may be used directly to undump these bytes: -*
 {@code
+ * Class to undump compiled lua bytecode into a {@link Prototype} instances.
+ * 

+ * The {@link LoadState} class provides the default {@link Globals.Undumper} + * which is used to undump a string of bytes that represent a lua binary file + * using either the C-based lua compiler, or luaj's + * {@link org.luaj.vm2.compiler.LuaC} compiler. + *

+ * The canonical method to load and execute code is done indirectly using the + * Globals: + * + *

+ * {
+ * 	@code
+ * 	Globals globals = JsePlatform.standardGlobals();
+ * 	LuaValue chunk = globasl.load("print('hello, world')", "main.lua");
+ * 	chunk.call();
+ * }
+ * 
+ * + * This should work regardless of which {@link Globals.Compiler} or + * {@link Globals.Undumper} have been installed. + *

+ * By default, when using {@link org.luaj.vm2.lib.jse.JsePlatform} or + * {@link org.luaj.vm2.lib.jme.JmePlatform} to construct globals, the + * {@link LoadState} default undumper is installed as the default + * {@link Globals.Undumper}. + *

+ * + * A lua binary file is created via the {@link org.luaj.vm2.compiler.DumpState} + * class : + * + *

+ * {
+ * 	@code
+ * 	Globals globals = JsePlatform.standardGlobals();
+ * 	Prototype p = globals.compilePrototype(new StringReader("print('hello, world')"), "main.lua");
+ * 	ByteArrayOutputStream o = new ByteArrayOutputStream();
+ * 	org.luaj.vm2.compiler.DumpState.dump(p, o, false);
+ * 	byte[] lua_binary_file_bytes = o.toByteArray();
+ * }
+ * 
+ * + * The {@link LoadState}'s default undumper {@link #instance} may be used + * directly to undump these bytes: + * + *
+ *  {@code
 * Prototypep = LoadState.instance.undump(new ByteArrayInputStream(lua_binary_file_bytes), "main.lua");
 * LuaClosure c = new LuaClosure(p, globals);
 * c.call();
-* } 
-* -* -* More commonly, the {@link Globals.Undumper} may be used to undump them: -*
 {@code
-* Prototype p = globals.loadPrototype(new ByteArrayInputStream(lua_binary_file_bytes), "main.lua", "b");
-* LuaClosure c = new LuaClosure(p, globals);
-* c.call();
-* } 
-* -* @see Globals.Compiler -* @see Globals.Undumper -* @see LuaClosure -* @see LuaFunction -* @see org.luaj.vm2.compiler.LuaC -* @see org.luaj.vm2.luajc.LuaJC -* @see Globals#compiler -* @see Globals#load(InputStream, String, LuaValue) -*/ +* } + *
+ * + * + * More commonly, the {@link Globals.Undumper} may be used to undump them: + * + *
+ * {
+ * 	@code
+ * 	Prototype p = globals.loadPrototype(new ByteArrayInputStream(lua_binary_file_bytes), "main.lua", "b");
+ * 	LuaClosure c = new LuaClosure(p, globals);
+ * 	c.call();
+ * }
+ * 
+ * + * @see Globals.Compiler + * @see Globals.Undumper + * @see LuaClosure + * @see LuaFunction + * @see org.luaj.vm2.compiler.LuaC + * @see org.luaj.vm2.luajc.LuaJC + * @see Globals#compiler + * @see Globals#load(InputStream, String, LuaValue) + */ public class LoadState { - /** Shared instance of Globals.Undumper to use loading prototypes from binary lua files */ + /** + * Shared instance of Globals.Undumper to use loading prototypes from binary + * lua files + */ public static final Globals.Undumper instance = new GlobalsUndumper(); - - /** format corresponding to non-number-patched lua, all numbers are floats or doubles */ - public static final int NUMBER_FORMAT_FLOATS_OR_DOUBLES = 0; + + /** + * format corresponding to non-number-patched lua, all numbers are floats or + * doubles + */ + public static final int NUMBER_FORMAT_FLOATS_OR_DOUBLES = 0; /** format corresponding to non-number-patched lua, all numbers are ints */ - public static final int NUMBER_FORMAT_INTS_ONLY = 1; - - /** format corresponding to number-patched lua, all numbers are 32-bit (4 byte) ints */ - public static final int NUMBER_FORMAT_NUM_PATCH_INT32 = 4; - + public static final int NUMBER_FORMAT_INTS_ONLY = 1; + + /** + * format corresponding to number-patched lua, all numbers are 32-bit (4 + * byte) ints + */ + public static final int NUMBER_FORMAT_NUM_PATCH_INT32 = 4; + // type constants - public static final int LUA_TINT = (-2); - public static final int LUA_TNONE = (-1); - public static final int LUA_TNIL = 0; - public static final int LUA_TBOOLEAN = 1; - public static final int LUA_TLIGHTUSERDATA = 2; - public static final int LUA_TNUMBER = 3; - public static final int LUA_TSTRING = 4; - public static final int LUA_TTABLE = 5; - public static final int LUA_TFUNCTION = 6; - public static final int LUA_TUSERDATA = 7; - public static final int LUA_TTHREAD = 8; - public static final int LUA_TVALUE = 9; - - /** The character encoding to use for file encoding. Null means the default encoding */ + public static final int LUA_TINT = -2; + public static final int LUA_TNONE = -1; + public static final int LUA_TNIL = 0; + public static final int LUA_TBOOLEAN = 1; + public static final int LUA_TLIGHTUSERDATA = 2; + public static final int LUA_TNUMBER = 3; + public static final int LUA_TSTRING = 4; + public static final int LUA_TTABLE = 5; + public static final int LUA_TFUNCTION = 6; + public static final int LUA_TUSERDATA = 7; + public static final int LUA_TTHREAD = 8; + public static final int LUA_TVALUE = 9; + + /** + * The character encoding to use for file encoding. Null means the default + * encoding + */ public static String encoding = null; - + /** Signature byte indicating the file is a compiled binary chunk */ - public static final byte[] LUA_SIGNATURE = { '\033', 'L', 'u', 'a' }; + public static final byte[] LUA_SIGNATURE = { '\033', 'L', 'u', 'a' }; /** Data to catch conversion errors */ public static final byte[] LUAC_TAIL = { (byte) 0x19, (byte) 0x93, '\r', '\n', (byte) 0x1a, '\n', }; - /** Name for compiled chunks */ public static final String SOURCE_BINARY_STRING = "binary string"; - /** for header of binary files -- this is Lua 5.2 */ - public static final int LUAC_VERSION = 0x52; + public static final int LUAC_VERSION = 0x52; /** for header of binary files -- this is the official format */ - public static final int LUAC_FORMAT = 0; + public static final int LUAC_FORMAT = 0; /** size of header of binary files */ - public static final int LUAC_HEADERSIZE = 12; + public static final int LUAC_HEADERSIZE = 12; // values read from the header private int luacVersion; @@ -144,7 +169,7 @@ public class LoadState { private int luacSizeofSizeT; private int luacSizeofInstruction; private int luacSizeofLuaNumber; - private int luacNumberFormat; + private int luacNumberFormat; /** input stream from which we are loading */ public final DataInputStream is; @@ -152,135 +177,148 @@ public class LoadState { /** Name of what is being loaded? */ String name; - private static final LuaValue[] NOVALUES = {}; - private static final Prototype[] NOPROTOS = {}; - private static final LocVars[] NOLOCVARS = {}; - private static final Upvaldesc[] NOUPVALDESCS = {}; - private static final int[] NOINTS = {}; - + private static final LuaValue[] NOVALUES = {}; + private static final Prototype[] NOPROTOS = {}; + private static final LocVars[] NOLOCVARS = {}; + private static final Upvaldesc[] NOUPVALDESCS = {}; + private static final int[] NOINTS = {}; + /** Read buffer */ private byte[] buf = new byte[512]; - /** Install this class as the standard Globals.Undumper for the supplied Globals */ + /** + * Install this class as the standard Globals.Undumper for the supplied + * Globals + */ public static void install(Globals globals) { globals.undumper = instance; } - - /** Load a 4-byte int value from the input stream + + /** + * Load a 4-byte int value from the input stream + * * @return the int value laoded. **/ int loadInt() throws IOException { - is.readFully(buf,0,4); - return luacLittleEndian? - (buf[3] << 24) | ((0xff & buf[2]) << 16) | ((0xff & buf[1]) << 8) | (0xff & buf[0]): - (buf[0] << 24) | ((0xff & buf[1]) << 16) | ((0xff & buf[2]) << 8) | (0xff & buf[3]); + is.readFully(buf, 0, 4); + return luacLittleEndian? buf[3]<<24 | (0xff & buf[2])<<16 | (0xff & buf[1])<<8 | 0xff & buf[0] + : buf[0]<<24 | (0xff & buf[1])<<16 | (0xff & buf[2])<<8 | 0xff & buf[3]; } - - /** Load an array of int values from the input stream + + /** + * Load an array of int values from the input stream + * * @return the array of int values laoded. **/ int[] loadIntArray() throws IOException { int n = loadInt(); - if ( n == 0 ) + if (n == 0) return NOINTS; - + // read all data at once - int m = n << 2; - if ( buf.length < m ) + int m = n<<2; + if (buf.length < m) buf = new byte[m]; - is.readFully(buf,0,m); + is.readFully(buf, 0, m); int[] array = new int[n]; - for ( int i=0, j=0; i> 52) & 0x7ffL) - 1023; - - if ( e >= 0 && e < 31 ) { + + int e = (int) (bits>>52 & 0x7ffL)-1023; + + if (e >= 0 && e < 31) { long f = bits & 0xFFFFFFFFFFFFFL; - int shift = 52 - e; - long intPrecMask = ( 1L << shift ) - 1; - if ( ( f & intPrecMask ) == 0 ) { - int intValue = (int)( f >> shift ) | ( 1 << e ); - return LuaInteger.valueOf( ( ( bits >> 63 ) != 0 ) ? -intValue : intValue ); + int shift = 52-e; + long intPrecMask = (1L<>shift) | 1<>63 != 0? -intValue: intValue); } } - - return LuaValue.valueOf( Double.longBitsToDouble(bits) ); + + return LuaValue.valueOf(Double.longBitsToDouble(bits)); } - + /** * Load a number from a binary chunk + * * @return the {@link LuaValue} loaded * @throws IOException if an i/o exception occurs */ LuaValue loadNumber() throws IOException { - if ( luacNumberFormat == NUMBER_FORMAT_INTS_ONLY ) { - return LuaInteger.valueOf( loadInt() ); + if (luacNumberFormat == NUMBER_FORMAT_INTS_ONLY) { + return LuaInteger.valueOf(loadInt()); } else { - return longBitsToLuaNumber( loadInt64() ); + return longBitsToLuaNumber(loadInt64()); } } /** * Load a list of constants from a binary chunk + * * @param f the function prototype * @throws IOException if an i/o exception occurs */ void loadConstants(Prototype f) throws IOException { int n = loadInt(); - LuaValue[] values = n>0? new LuaValue[n]: NOVALUES; - for ( int i=0; i 0? new LuaValue[n]: NOVALUES; + for (int i = 0; i < n; i++) { + switch (is.readByte()) { case LUA_TNIL: values[i] = LuaValue.NIL; break; case LUA_TBOOLEAN: - values[i] = (0 != is.readUnsignedByte()? LuaValue.TRUE: LuaValue.FALSE); + values[i] = 0 != is.readUnsignedByte()? LuaValue.TRUE: LuaValue.FALSE; break; case LUA_TINT: - values[i] = LuaInteger.valueOf( loadInt() ); + values[i] = LuaInteger.valueOf(loadInt()); break; case LUA_TNUMBER: values[i] = loadNumber(); @@ -293,49 +331,50 @@ public class LoadState { } } f.k = values; - + n = loadInt(); - Prototype[] protos = n>0? new Prototype[n]: NOPROTOS; - for ( int i=0; i 0? new Prototype[n]: NOPROTOS; + for (int i = 0; i < n; i++) protos[i] = loadFunction(f.source); f.p = protos; } - void loadUpvalues(Prototype f) throws IOException { int n = loadInt(); - f.upvalues = n>0? new Upvaldesc[n]: NOUPVALDESCS; - for (int i=0; i 0? new Upvaldesc[n]: NOUPVALDESCS; + for (int i = 0; i < n; i++) { boolean instack = is.readByte() != 0; - int idx = ((int) is.readByte()) & 0xff; + int idx = is.readByte() & 0xff; f.upvalues[i] = new Upvaldesc(null, instack, idx); } } /** * Load the debug info for a function prototype + * * @param f the function Prototype * @throws IOException if there is an i/o exception */ - void loadDebug( Prototype f ) throws IOException { + void loadDebug(Prototype f) throws IOException { f.source = loadString(); f.lineinfo = loadIntArray(); int n = loadInt(); - f.locvars = n>0? new LocVars[n]: NOLOCVARS; - for ( int i=0; i 0? new LocVars[n]: NOLOCVARS; + for (int i = 0; i < n; i++) { LuaString varname = loadString(); int startpc = loadInt(); int endpc = loadInt(); f.locvars[i] = new LocVars(varname, startpc, endpc); } - + n = loadInt(); - for ( int i=0; i - * This is a direct translation of C lua distribution header file constants - * for bytecode creation and processing. + * This is a direct translation of C lua distribution header file constants for + * bytecode creation and processing. */ public class Lua { /** version is supplied by ant build task */ public static final String _VERSION = "Luaj 0.0"; - + /** use return values from previous op */ public static final int LUA_MULTRET = -1; @@ -46,7 +45,7 @@ public class Lua { `C' : 9 bits `Bx' : 18 bits (`B' and `C' together) `sBx' : signed Bx - + A signed argument is represented in excess K; that is, the number value is the unsigned value minus K. K is exactly the maximum value for that argument (so that -max is represented by 0, and +max is @@ -54,46 +53,44 @@ public class Lua { unsigned argument. ===========================================================================*/ - /* basic instruction format */ - public static final int iABC = 0; - public static final int iABx = 1; - public static final int iAsBx = 2; - public static final int iAx = 3; - + public static final int iABC = 0; + public static final int iABx = 1; + public static final int iAsBx = 2; + public static final int iAx = 3; /* ** size and position of opcode arguments. */ - public static final int SIZE_C = 9; - public static final int SIZE_B = 9; - public static final int SIZE_Bx = (SIZE_C + SIZE_B); - public static final int SIZE_A = 8; - public static final int SIZE_Ax = (SIZE_C + SIZE_B + SIZE_A); + public static final int SIZE_C = 9; + public static final int SIZE_B = 9; + public static final int SIZE_Bx = SIZE_C+SIZE_B; + public static final int SIZE_A = 8; + public static final int SIZE_Ax = SIZE_C+SIZE_B+SIZE_A; - public static final int SIZE_OP = 6; + public static final int SIZE_OP = 6; - public static final int POS_OP = 0; - public static final int POS_A = (POS_OP + SIZE_OP); - public static final int POS_C = (POS_A + SIZE_A); - public static final int POS_B = (POS_C + SIZE_C); - public static final int POS_Bx = POS_C; - public static final int POS_Ax = POS_A; + public static final int POS_OP = 0; + public static final int POS_A = POS_OP+SIZE_OP; + public static final int POS_C = POS_A+SIZE_A; + public static final int POS_B = POS_C+SIZE_C; + public static final int POS_Bx = POS_C; + public static final int POS_Ax = POS_A; - public static final int MAX_OP = ((1<>1); /* `sBx' is signed */ - public static final int MAXARG_Ax = ((1<>1; /* `sBx' is signed */ + public static final int MAXARG_Ax = (1<> POS_OP) & MAX_OP; + return i>>POS_OP & MAX_OP; } public static int GETARG_A(int i) { - return (i >> POS_A) & MAXARG_A; + return i>>POS_A & MAXARG_A; } public static int GETARG_Ax(int i) { - return (i >> POS_Ax) & MAXARG_Ax; + return i>>POS_Ax & MAXARG_Ax; } public static int GETARG_B(int i) { - return (i >> POS_B) & MAXARG_B; + return i>>POS_B & MAXARG_B; } public static int GETARG_C(int i) { - return (i >> POS_C) & MAXARG_C; + return i>>POS_C & MAXARG_C; } public static int GETARG_Bx(int i) { - return (i >> POS_Bx) & MAXARG_Bx; + return i>>POS_Bx & MAXARG_Bx; } public static int GETARG_sBx(int i) { - return ((i >> POS_Bx) & MAXARG_Bx) - MAXARG_sBx; + return (i>>POS_Bx & MAXARG_Bx)-MAXARG_sBx; } - /* ** Macros to operate RK indices */ /** this bit 1 means constant (0 means register) */ - public static final int BITRK = (1 << (SIZE_B - 1)); + public static final int BITRK = 1<= R(A - 1) */ - public static final int OP_EQ = 24; /* A B C if ((RK(B) == RK(C)) ~= A) then pc++ */ - public static final int OP_LT = 25; /* A B C if ((RK(B) < RK(C)) ~= A) then pc++ */ - public static final int OP_LE = 26; /* A B C if ((RK(B) <= RK(C)) ~= A) then pc++ */ + public static final int OP_EQ = 24; /* A B C if ((RK(B) == RK(C)) ~= A) then pc++ */ + public static final int OP_LT = 25; /* A B C if ((RK(B) < RK(C)) ~= A) then pc++ */ + public static final int OP_LE = 26; /* A B C if ((RK(B) <= RK(C)) ~= A) then pc++ */ - public static final int OP_TEST = 27; /* A C if not (R(A) <=> C) then pc++ */ + public static final int OP_TEST = 27; /* A C if not (R(A) <=> C) then pc++ */ public static final int OP_TESTSET = 28; /* A B C if (R(B) <=> C) then R(A) := R(B) else pc++ */ - public static final int OP_CALL = 29; /* A B C R(A), ... ,R(A+C-2) := R(A)(R(A+1), ... ,R(A+B-1)) */ + public static final int OP_CALL = 29; /* A B C R(A), ... ,R(A+C-2) := R(A)(R(A+1), ... ,R(A+B-1)) */ public static final int OP_TAILCALL = 30; /* A B C return R(A)(R(A+1), ... ,R(A+B-1)) */ - public static final int OP_RETURN = 31; /* A B return R(A), ... ,R(A+B-2) (see note) */ + public static final int OP_RETURN = 31; /* A B return R(A), ... ,R(A+B-2) (see note) */ public static final int OP_FORLOOP = 32; /* A sBx R(A)+=R(A+2); - if R(A) @@ -242,28 +235,27 @@ public class Lua { public static final int OP_NEQ = 61; // ~= public static final int OP_AND = 60; // and public static final int OP_OR = 59; // or - + /*=========================================================================== Notes: (*) In OP_CALL, if (B == 0) then B = top. C is the number of returns - 1, and can be 0: OP_CALL then sets `top' to last_result+1, so next open instruction (OP_CALL, OP_RETURN, OP_SETLIST) may use `top'. - + (*) In OP_VARARG, if (B == 0) then use actual number of varargs and set top (like in OP_CALL with C == 0). - + (*) In OP_RETURN, if (B == 0) then return up to `top' - + (*) In OP_SETLIST, if (B == 0) then B = `top'; if (C == 0) then next `instruction' is real C - + (*) For comparisons, A specifies what condition the test should accept (true or false). - + (*) All `skips' (pc++) assume that next instruction is a jump ===========================================================================*/ - /* ** masks for instruction properties. The format is: ** bits 0-1: op mode @@ -273,69 +265,73 @@ public class Lua { ** bit 7: operator is a test */ - public static final int OpArgN = 0; /* argument is not used */ - public static final int OpArgU = 1; /* argument is used */ - public static final int OpArgR = 2; /* argument is a register or a jump offset */ - public static final int OpArgK = 3; /* argument is a constant or register/constant */ + public static final int OpArgN = 0; /* argument is not used */ + public static final int OpArgU = 1; /* argument is used */ + public static final int OpArgR = 2; /* argument is a register or a jump offset */ + public static final int OpArgK = 3; /* argument is a constant or register/constant */ - public static final int[] luaP_opmodes = { - /* T A B C mode opcode */ - (0<<7) | (1<<6) | (OpArgR<<4) | (OpArgN<<2) | (iABC), /* OP_MOVE */ - (0<<7) | (1<<6) | (OpArgK<<4) | (OpArgN<<2) | (iABx), /* OP_LOADK */ - (0<<7) | (1<<6) | (OpArgN<<4) | (OpArgN<<2) | (iABx), /* OP_LOADKX */ - (0<<7) | (1<<6) | (OpArgU<<4) | (OpArgU<<2) | (iABC), /* OP_LOADBOOL */ - (0<<7) | (1<<6) | (OpArgU<<4) | (OpArgN<<2) | (iABC), /* OP_LOADNIL */ - (0<<7) | (1<<6) | (OpArgU<<4) | (OpArgN<<2) | (iABC), /* OP_GETUPVAL */ - (0<<7) | (1<<6) | (OpArgU<<4) | (OpArgK<<2) | (iABC), /* OP_GETTABUP */ - (0<<7) | (1<<6) | (OpArgR<<4) | (OpArgK<<2) | (iABC), /* OP_GETTABLE */ - (0<<7) | (0<<6) | (OpArgK<<4) | (OpArgK<<2) | (iABC), /* OP_SETTABUP */ - (0<<7) | (0<<6) | (OpArgU<<4) | (OpArgN<<2) | (iABC), /* OP_SETUPVAL */ - (0<<7) | (0<<6) | (OpArgK<<4) | (OpArgK<<2) | (iABC), /* OP_SETTABLE */ - (0<<7) | (1<<6) | (OpArgU<<4) | (OpArgU<<2) | (iABC), /* OP_NEWTABLE */ - (0<<7) | (1<<6) | (OpArgR<<4) | (OpArgK<<2) | (iABC), /* OP_SELF */ - (0<<7) | (1<<6) | (OpArgK<<4) | (OpArgK<<2) | (iABC), /* OP_ADD */ - (0<<7) | (1<<6) | (OpArgK<<4) | (OpArgK<<2) | (iABC), /* OP_SUB */ - (0<<7) | (1<<6) | (OpArgK<<4) | (OpArgK<<2) | (iABC), /* OP_MUL */ - (0<<7) | (1<<6) | (OpArgK<<4) | (OpArgK<<2) | (iABC), /* OP_DIV */ - (0<<7) | (1<<6) | (OpArgK<<4) | (OpArgK<<2) | (iABC), /* OP_MOD */ - (0<<7) | (1<<6) | (OpArgK<<4) | (OpArgK<<2) | (iABC), /* OP_POW */ - (0<<7) | (1<<6) | (OpArgR<<4) | (OpArgN<<2) | (iABC), /* OP_UNM */ - (0<<7) | (1<<6) | (OpArgR<<4) | (OpArgN<<2) | (iABC), /* OP_NOT */ - (0<<7) | (1<<6) | (OpArgR<<4) | (OpArgN<<2) | (iABC), /* OP_LEN */ - (0<<7) | (1<<6) | (OpArgR<<4) | (OpArgR<<2) | (iABC), /* OP_CONCAT */ - (0<<7) | (0<<6) | (OpArgR<<4) | (OpArgN<<2) | (iAsBx), /* OP_JMP */ - (1<<7) | (0<<6) | (OpArgK<<4) | (OpArgK<<2) | (iABC), /* OP_EQ */ - (1<<7) | (0<<6) | (OpArgK<<4) | (OpArgK<<2) | (iABC), /* OP_LT */ - (1<<7) | (0<<6) | (OpArgK<<4) | (OpArgK<<2) | (iABC), /* OP_LE */ - (1<<7) | (0<<6) | (OpArgN<<4) | (OpArgU<<2) | (iABC), /* OP_TEST */ - (1<<7) | (1<<6) | (OpArgR<<4) | (OpArgU<<2) | (iABC), /* OP_TESTSET */ - (0<<7) | (1<<6) | (OpArgU<<4) | (OpArgU<<2) | (iABC), /* OP_CALL */ - (0<<7) | (1<<6) | (OpArgU<<4) | (OpArgU<<2) | (iABC), /* OP_TAILCALL */ - (0<<7) | (0<<6) | (OpArgU<<4) | (OpArgN<<2) | (iABC), /* OP_RETURN */ - (0<<7) | (1<<6) | (OpArgR<<4) | (OpArgN<<2) | (iAsBx), /* OP_FORLOOP */ - (0<<7) | (1<<6) | (OpArgR<<4) | (OpArgN<<2) | (iAsBx), /* OP_FORPREP */ - (0<<7) | (0<<6) | (OpArgN<<4) | (OpArgU<<2) | (iABC), /* OP_TFORCALL */ - (1<<7) | (1<<6) | (OpArgR<<4) | (OpArgN<<2) | (iAsBx), /* OP_TFORLOOP */ - (0<<7) | (0<<6) | (OpArgU<<4) | (OpArgU<<2) | (iABC), /* OP_SETLIST */ - (0<<7) | (1<<6) | (OpArgU<<4) | (OpArgN<<2) | (iABx), /* OP_CLOSURE */ - (0<<7) | (1<<6) | (OpArgU<<4) | (OpArgN<<2) | (iABC), /* OP_VARARG */ - (0<<7) | (0<<6) | (OpArgU<<4) | (OpArgU<<2) | (iAx), /* OP_EXTRAARG */ - }; + public static final int[] luaP_opmodes = { + /* T A B C mode opcode */ + 0<<7 | 1<<6 | OpArgR<<4 | OpArgN<<2 | iABC, /* OP_MOVE */ + 0<<7 | 1<<6 | OpArgK<<4 | OpArgN<<2 | iABx, /* OP_LOADK */ + 0<<7 | 1<<6 | OpArgN<<4 | OpArgN<<2 | iABx, /* OP_LOADKX */ + 0<<7 | 1<<6 | OpArgU<<4 | OpArgU<<2 | iABC, /* OP_LOADBOOL */ + 0<<7 | 1<<6 | OpArgU<<4 | OpArgN<<2 | iABC, /* OP_LOADNIL */ + 0<<7 | 1<<6 | OpArgU<<4 | OpArgN<<2 | iABC, /* OP_GETUPVAL */ + 0<<7 | 1<<6 | OpArgU<<4 | OpArgK<<2 | iABC, /* OP_GETTABUP */ + 0<<7 | 1<<6 | OpArgR<<4 | OpArgK<<2 | iABC, /* OP_GETTABLE */ + 0<<7 | 0<<6 | OpArgK<<4 | OpArgK<<2 | iABC, /* OP_SETTABUP */ + 0<<7 | 0<<6 | OpArgU<<4 | OpArgN<<2 | iABC, /* OP_SETUPVAL */ + 0<<7 | 0<<6 | OpArgK<<4 | OpArgK<<2 | iABC, /* OP_SETTABLE */ + 0<<7 | 1<<6 | OpArgU<<4 | OpArgU<<2 | iABC, /* OP_NEWTABLE */ + 0<<7 | 1<<6 | OpArgR<<4 | OpArgK<<2 | iABC, /* OP_SELF */ + 0<<7 | 1<<6 | OpArgK<<4 | OpArgK<<2 | iABC, /* OP_ADD */ + 0<<7 | 1<<6 | OpArgK<<4 | OpArgK<<2 | iABC, /* OP_SUB */ + 0<<7 | 1<<6 | OpArgK<<4 | OpArgK<<2 | iABC, /* OP_MUL */ + 0<<7 | 1<<6 | OpArgK<<4 | OpArgK<<2 | iABC, /* OP_DIV */ + 0<<7 | 1<<6 | OpArgK<<4 | OpArgK<<2 | iABC, /* OP_MOD */ + 0<<7 | 1<<6 | OpArgK<<4 | OpArgK<<2 | iABC, /* OP_POW */ + 0<<7 | 1<<6 | OpArgR<<4 | OpArgN<<2 | iABC, /* OP_UNM */ + 0<<7 | 1<<6 | OpArgR<<4 | OpArgN<<2 | iABC, /* OP_NOT */ + 0<<7 | 1<<6 | OpArgR<<4 | OpArgN<<2 | iABC, /* OP_LEN */ + 0<<7 | 1<<6 | OpArgR<<4 | OpArgR<<2 | iABC, /* OP_CONCAT */ + 0<<7 | 0<<6 | OpArgR<<4 | OpArgN<<2 | iAsBx, /* OP_JMP */ + 1<<7 | 0<<6 | OpArgK<<4 | OpArgK<<2 | iABC, /* OP_EQ */ + 1<<7 | 0<<6 | OpArgK<<4 | OpArgK<<2 | iABC, /* OP_LT */ + 1<<7 | 0<<6 | OpArgK<<4 | OpArgK<<2 | iABC, /* OP_LE */ + 1<<7 | 0<<6 | OpArgN<<4 | OpArgU<<2 | iABC, /* OP_TEST */ + 1<<7 | 1<<6 | OpArgR<<4 | OpArgU<<2 | iABC, /* OP_TESTSET */ + 0<<7 | 1<<6 | OpArgU<<4 | OpArgU<<2 | iABC, /* OP_CALL */ + 0<<7 | 1<<6 | OpArgU<<4 | OpArgU<<2 | iABC, /* OP_TAILCALL */ + 0<<7 | 0<<6 | OpArgU<<4 | OpArgN<<2 | iABC, /* OP_RETURN */ + 0<<7 | 1<<6 | OpArgR<<4 | OpArgN<<2 | iAsBx, /* OP_FORLOOP */ + 0<<7 | 1<<6 | OpArgR<<4 | OpArgN<<2 | iAsBx, /* OP_FORPREP */ + 0<<7 | 0<<6 | OpArgN<<4 | OpArgU<<2 | iABC, /* OP_TFORCALL */ + 1<<7 | 1<<6 | OpArgR<<4 | OpArgN<<2 | iAsBx, /* OP_TFORLOOP */ + 0<<7 | 0<<6 | OpArgU<<4 | OpArgU<<2 | iABC, /* OP_SETLIST */ + 0<<7 | 1<<6 | OpArgU<<4 | OpArgN<<2 | iABx, /* OP_CLOSURE */ + 0<<7 | 1<<6 | OpArgU<<4 | OpArgN<<2 | iABC, /* OP_VARARG */ + 0<<7 | 0<<6 | OpArgU<<4 | OpArgU<<2 | iAx, /* OP_EXTRAARG */ + }; public static int getOpMode(int m) { return luaP_opmodes[m] & 3; } + public static int getBMode(int m) { - return (luaP_opmodes[m] >> 4) & 3; + return luaP_opmodes[m]>>4 & 3; } + public static int getCMode(int m) { - return (luaP_opmodes[m] >> 2) & 3; + return luaP_opmodes[m]>>2 & 3; } + public static boolean testAMode(int m) { - return 0 != (luaP_opmodes[m] & (1 << 6)); + return 0 != (luaP_opmodes[m] & 1<<6); } + public static boolean testTMode(int m) { - return 0 != (luaP_opmodes[m] & (1 << 7)); + return 0 != (luaP_opmodes[m] & 1<<7); } /* number of list items to accumulate before a SETLIST instruction */ @@ -343,19 +339,19 @@ public class Lua { private static final int MAXSRC = 80; - public static String chunkid( String source ) { - if ( source.startsWith("=") ) - return source.substring(1); - String end = ""; - if ( source.startsWith("@") ) { - source = source.substring(1); - } else { - source = "[string \""+source; - end = "\"]"; - } - int n = source.length() + end.length(); - if ( n > MAXSRC ) - source = source.substring(0,MAXSRC-end.length()-3) + "..."; - return source + end; + public static String chunkid(String source) { + if (source.startsWith("=")) + return source.substring(1); + String end = ""; + if (source.startsWith("@")) { + source = source.substring(1); + } else { + source = "[string \"" + source; + end = "\"]"; + } + int n = source.length()+end.length(); + if (n > MAXSRC) + source = source.substring(0, MAXSRC-end.length()-3) + "..."; + return source+end; } } diff --git a/src/core/org/luaj/vm2/LuaBoolean.java b/luaj-core/src/main/java/org/luaj/vm2/LuaBoolean.java similarity index 78% rename from src/core/org/luaj/vm2/LuaBoolean.java rename to luaj-core/src/main/java/org/luaj/vm2/LuaBoolean.java index 33103415..fe50a61f 100644 --- a/src/core/org/luaj/vm2/LuaBoolean.java +++ b/luaj-core/src/main/java/org/luaj/vm2/LuaBoolean.java @@ -10,7 +10,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -22,18 +22,18 @@ package org.luaj.vm2; /** - * Extension of {@link LuaValue} which can hold a Java boolean as its value. + * Extension of {@link LuaValue} which can hold a Java boolean as its value. *

- * These instance are not instantiated directly by clients. - * Instead, there are exactly twon instances of this class, - * {@link LuaValue#TRUE} and {@link LuaValue#FALSE} - * representing the lua values {@code true} and {@code false}. - * The function {@link LuaValue#valueOf(boolean)} will always - * return one of these two values. + * These instance are not instantiated directly by clients. Instead, there are + * exactly twon instances of this class, {@link LuaValue#TRUE} and + * {@link LuaValue#FALSE} representing the lua values {@code true} and + * {@code false}. The function {@link LuaValue#valueOf(boolean)} will always + * return one of these two values. *

- * Any {@link LuaValue} can be converted to its equivalent - * boolean representation using {@link LuaValue#toboolean()} + * Any {@link LuaValue} can be converted to its equivalent boolean + * representation using {@link LuaValue#toboolean()} *

+ * * @see LuaValue * @see LuaValue#valueOf(boolean) * @see LuaValue#TRUE @@ -43,10 +43,10 @@ public final class LuaBoolean extends LuaValue { /** The singleton instance representing lua {@code true} */ static final LuaBoolean _TRUE = new LuaBoolean(true); - + /** The singleton instance representing lua {@code false} */ static final LuaBoolean _FALSE = new LuaBoolean(false); - + /** Shared static metatable for boolean values represented in lua. */ public static LuaValue s_metatable; @@ -57,47 +57,57 @@ public final class LuaBoolean extends LuaValue { this.v = b; } + @Override public int type() { return LuaValue.TBOOLEAN; } + @Override public String typename() { return "boolean"; } + @Override public boolean isboolean() { return true; } + @Override public LuaValue not() { - return v ? FALSE : LuaValue.TRUE; + return v? FALSE: LuaValue.TRUE; } /** * Return the boolean value for this boolean + * * @return value as a Java boolean */ public boolean booleanValue() { return v; } + @Override public boolean toboolean() { return v; } + @Override public String tojstring() { - return v ? "true" : "false"; + return v? "true": "false"; } + @Override public boolean optboolean(boolean defval) { return this.v; } - + + @Override public boolean checkboolean() { return v; } - - public LuaValue getmetatable() { - return s_metatable; + + @Override + public LuaValue getmetatable() { + return s_metatable; } } diff --git a/src/core/org/luaj/vm2/LuaClosure.java b/luaj-core/src/main/java/org/luaj/vm2/LuaClosure.java similarity index 52% rename from src/core/org/luaj/vm2/LuaClosure.java rename to luaj-core/src/main/java/org/luaj/vm2/LuaClosure.java index 46a3556f..7ceb0dd8 100644 --- a/src/core/org/luaj/vm2/LuaClosure.java +++ b/luaj-core/src/main/java/org/luaj/vm2/LuaClosure.java @@ -10,7 +10,7 @@ * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. -* +* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -26,44 +26,56 @@ import org.luaj.vm2.lib.DebugLib.CallFrame; /** * Extension of {@link LuaFunction} which executes lua bytecode. *

- * A {@link LuaClosure} is a combination of a {@link Prototype} - * and a {@link LuaValue} to use as an environment for execution. - * Normally the {@link LuaValue} is a {@link Globals} in which case the environment - * will contain standard lua libraries. - * + * A {@link LuaClosure} is a combination of a {@link Prototype} and a + * {@link LuaValue} to use as an environment for execution. Normally the + * {@link LuaValue} is a {@link Globals} in which case the environment will + * contain standard lua libraries. + * *

* There are three main ways {@link LuaClosure} instances are created: *

    *
  • Construct an instance using {@link #LuaClosure(Prototype, LuaValue)}
  • - *
  • Construct it indirectly by loading a chunk via {@link Globals#load(java.io.Reader, String)} - *
  • Execute the lua bytecode {@link Lua#OP_CLOSURE} as part of bytecode processing + *
  • Construct it indirectly by loading a chunk via + * {@link Globals#load(java.io.Reader, String)} + *
  • Execute the lua bytecode {@link Lua#OP_CLOSURE} as part of bytecode + * processing *
*

- * To construct it directly, the {@link Prototype} is typically created via a compiler such as - * {@link org.luaj.vm2.compiler.LuaC}: - *

 {@code
- * String script = "print( 'hello, world' )";
- * InputStream is = new ByteArrayInputStream(script.getBytes());
- * Prototype p = LuaC.instance.compile(is, "script");
- * LuaValue globals = JsePlatform.standardGlobals();
- * LuaClosure f = new LuaClosure(p, globals);
- * f.call();
- * }
+ * To construct it directly, the {@link Prototype} is typically created via a + * compiler such as {@link org.luaj.vm2.compiler.LuaC}: + * + *
+ * {
+ * 	@code
+ * 	String script = "print( 'hello, world' )";
+ * 	InputStream is = new ByteArrayInputStream(script.getBytes());
+ * 	Prototype p = LuaC.instance.compile(is, "script");
+ * 	LuaValue globals = JsePlatform.standardGlobals();
+ * 	LuaClosure f = new LuaClosure(p, globals);
+ * 	f.call();
+ * }
+ * 
*

- * To construct it indirectly, the {@link Globals#load(java.io.Reader, String)} method may be used: - *

 {@code
- * Globals globals = JsePlatform.standardGlobals();
- * LuaFunction f = globals.load(new StringReader(script), "script");
- * LuaClosure c = f.checkclosure();  // This may fail if LuaJC is installed.
- * c.call();
- * }
+ * To construct it indirectly, the {@link Globals#load(java.io.Reader, String)} + * method may be used: + * + *
+ * {
+ * 	@code
+ * 	Globals globals = JsePlatform.standardGlobals();
+ * 	LuaFunction f = globals.load(new StringReader(script), "script");
+ * 	LuaClosure c = f.checkclosure(); // This may fail if LuaJC is installed.
+ * 	c.call();
+ * }
+ * 
*

* In this example, the "checkclosure()" may fail if direct lua-to-java-bytecode - * compiling using LuaJC is installed, because no LuaClosure is created in that case - * and the value returned is a {@link LuaFunction} but not a {@link LuaClosure}. + * compiling using LuaJC is installed, because no LuaClosure is created in that + * case and the value returned is a {@link LuaFunction} but not a + * {@link LuaClosure}. *

- * Since a {@link LuaClosure} is a {@link LuaFunction} which is a {@link LuaValue}, - * all the value operations can be used directly such as: + * Since a {@link LuaClosure} is a {@link LuaFunction} which is a + * {@link LuaValue}, all the value operations can be used directly such as: *

    *
  • {@link LuaValue#call()}
  • *
  • {@link LuaValue#call(LuaValue)}
  • @@ -73,8 +85,9 @@ import org.luaj.vm2.lib.DebugLib.CallFrame; *
  • {@link LuaValue#method(String,LuaValue)}
  • *
  • {@link LuaValue#invokemethod(String)}
  • *
  • {@link LuaValue#invokemethod(String,Varargs)}
  • - *
  • ...
  • + *
  • ...
  • *
+ * * @see LuaValue * @see LuaFunction * @see LuaValue#isclosure() @@ -84,17 +97,20 @@ import org.luaj.vm2.lib.DebugLib.CallFrame; * @see Globals#compiler */ public class LuaClosure extends LuaFunction { - private static final UpValue[] NOUPVALUES = new UpValue[0]; - + private static final UpValue[] NOUPVALUES = {}; + public final Prototype p; public UpValue[] upValues; - + final Globals globals; - - /** Create a closure around a Prototype with a specific environment. - * If the prototype has upvalues, the environment will be written into the first upvalue. - * @param p the Prototype to construct this Closure for. + + /** + * Create a closure around a Prototype with a specific environment. If the + * prototype has upvalues, the environment will be written into the first + * upvalue. + * + * @param p the Prototype to construct this Closure for. * @param env the environment to associate with the closure. */ public LuaClosure(Prototype p, LuaValue env) { @@ -102,401 +118,467 @@ public class LuaClosure extends LuaFunction { this.initupvalue1(env); globals = env instanceof Globals? (Globals) env: null; } - + + @Override public void initupvalue1(LuaValue env) { if (p.upvalues == null || p.upvalues.length == 0) this.upValues = NOUPVALUES; else { this.upValues = new UpValue[p.upvalues.length]; - this.upValues[0] = new UpValue(new LuaValue[] {env}, 0); + this.upValues[0] = new UpValue(new LuaValue[] { env }, 0); } } - + @Override public boolean isclosure() { return true; } - + + @Override public LuaClosure optclosure(LuaClosure defval) { return this; } + @Override public LuaClosure checkclosure() { return this; } - + + @Override public String tojstring() { return "function: " + p.toString(); } - + private LuaValue[] getNewStack() { int max = p.maxstacksize; LuaValue[] stack = new LuaValue[max]; System.arraycopy(NILS, 0, stack, 0, max); return stack; } - + + @Override public final LuaValue call() { LuaValue[] stack = getNewStack(); - return execute(stack,NONE).arg1(); + return execute(stack, NONE).arg1(); } + @Override public final LuaValue call(LuaValue arg) { LuaValue[] stack = getNewStack(); - switch ( p.numparams ) { - default: stack[0]=arg; return execute(stack,NONE).arg1(); - case 0: return execute(stack,arg).arg1(); + switch (p.numparams) { + default: + stack[0] = arg; + return execute(stack, NONE).arg1(); + case 0: + return execute(stack, arg).arg1(); } } - + + @Override public final LuaValue call(LuaValue arg1, LuaValue arg2) { LuaValue[] stack = getNewStack(); - switch ( p.numparams ) { - default: stack[0]=arg1; stack[1]=arg2; return execute(stack,NONE).arg1(); - case 1: stack[0]=arg1; return execute(stack,arg2).arg1(); - case 0: return execute(stack,p.is_vararg!=0? varargsOf(arg1,arg2): NONE).arg1(); + switch (p.numparams) { + default: + stack[0] = arg1; + stack[1] = arg2; + return execute(stack, NONE).arg1(); + case 1: + stack[0] = arg1; + return execute(stack, arg2).arg1(); + case 0: + return execute(stack, p.is_vararg != 0? varargsOf(arg1, arg2): NONE).arg1(); } } + @Override public final LuaValue call(LuaValue arg1, LuaValue arg2, LuaValue arg3) { LuaValue[] stack = getNewStack(); - switch ( p.numparams ) { - default: stack[0]=arg1; stack[1]=arg2; stack[2]=arg3; return execute(stack,NONE).arg1(); - case 2: stack[0]=arg1; stack[1]=arg2; return execute(stack,arg3).arg1(); - case 1: stack[0]=arg1; return execute(stack,p.is_vararg!=0? varargsOf(arg2,arg3): NONE).arg1(); - case 0: return execute(stack,p.is_vararg!=0? varargsOf(arg1,arg2,arg3): NONE).arg1(); + switch (p.numparams) { + default: + stack[0] = arg1; + stack[1] = arg2; + stack[2] = arg3; + return execute(stack, NONE).arg1(); + case 2: + stack[0] = arg1; + stack[1] = arg2; + return execute(stack, arg3).arg1(); + case 1: + stack[0] = arg1; + return execute(stack, p.is_vararg != 0? varargsOf(arg2, arg3): NONE).arg1(); + case 0: + return execute(stack, p.is_vararg != 0? varargsOf(arg1, arg2, arg3): NONE).arg1(); } } + @Override public final Varargs invoke(Varargs varargs) { return onInvoke(varargs).eval(); } - + + @Override public final Varargs onInvoke(Varargs varargs) { LuaValue[] stack = getNewStack(); - for ( int i=0; i0? new UpValue[stack.length]: null; - + UpValue[] openups = p.p.length > 0? new UpValue[stack.length]: null; + // allow for debug hooks if (globals != null && globals.debuglib != null) - globals.debuglib.onCall( this, varargs, stack ); + globals.debuglib.onCall(this, varargs, stack); // process instructions try { for (; true; ++pc) { if (globals != null && globals.debuglib != null) - globals.debuglib.onInstruction( pc, v, top ); - + globals.debuglib.onInstruction(pc, v, top); + // pull out instruction i = code[pc]; - a = ((i>>6) & 0xff); - + a = i>>6 & 0xff; + // process the op code - switch ( i & 0x3f ) { - + switch (i & 0x3f) { + case Lua.OP_MOVE:/* A B R(A):= R(B) */ stack[a] = stack[i>>>23]; continue; - + case Lua.OP_LOADK:/* A Bx R(A):= Kst(Bx) */ stack[a] = k[i>>>14]; continue; - + case Lua.OP_LOADKX:/* A R(A) := Kst(extra arg) */ ++pc; i = code[pc]; if ((i & 0x3f) != Lua.OP_EXTRAARG) { int op = i & 0x3f; - throw new LuaError("OP_EXTRAARG expected after OP_LOADKX, got " + - (op < Print.OPNAMES.length - 1 ? Print.OPNAMES[op] : "UNKNOWN_OP_" + op)); + throw new LuaError("OP_EXTRAARG expected after OP_LOADKX, got " + + (op < Print.OPNAMES.length-1? Print.OPNAMES[op]: "UNKNOWN_OP_" + op)); } stack[a] = k[i>>>6]; continue; - + case Lua.OP_LOADBOOL:/* A B C R(A):= (Bool)B: if (C) pc++ */ - stack[a] = (i>>>23!=0)? LuaValue.TRUE: LuaValue.FALSE; - if ((i&(0x1ff<<14)) != 0) - ++pc; /* skip next instruction (if C) */ - continue; - + stack[a] = i>>>23 != 0? LuaValue.TRUE: LuaValue.FALSE; + if ((i & 0x1ff<<14) != 0) + ++pc; /* skip next instruction (if C) */ + continue; + case Lua.OP_LOADNIL: /* A B R(A):= ...:= R(A+B):= nil */ - for ( b=i>>>23; b-->=0; ) + for (b = i>>>23; b-- >= 0;) stack[a++] = LuaValue.NIL; continue; - + case Lua.OP_GETUPVAL: /* A B R(A):= UpValue[B] */ - stack[a] = upValues[i>>>23].getValue(); - continue; - + stack[a] = upValues[i>>>23].getValue(); + continue; + case Lua.OP_GETTABUP: /* A B C R(A) := UpValue[B][RK(C)] */ - stack[a] = upValues[i>>>23].getValue().get((c=(i>>14)&0x1ff)>0xff? k[c&0x0ff]: stack[c]); + stack[a] = upValues[i>>>23].getValue().get((c = i>>14 & 0x1ff) > 0xff? k[c & 0x0ff]: stack[c]); continue; - + case Lua.OP_GETTABLE: /* A B C R(A):= R(B)[RK(C)] */ - stack[a] = stack[i>>>23].get((c=(i>>14)&0x1ff)>0xff? k[c&0x0ff]: stack[c]); + stack[a] = stack[i>>>23].get((c = i>>14 & 0x1ff) > 0xff? k[c & 0x0ff]: stack[c]); continue; - + case Lua.OP_SETTABUP: /* A B C UpValue[A][RK(B)] := RK(C) */ - upValues[a].getValue().set(((b=i>>>23)>0xff? k[b&0x0ff]: stack[b]), (c=(i>>14)&0x1ff)>0xff? k[c&0x0ff]: stack[c]); + upValues[a].getValue().set((b = i>>>23) > 0xff? k[b & 0x0ff]: stack[b], + (c = i>>14 & 0x1ff) > 0xff? k[c & 0x0ff]: stack[c]); continue; - + case Lua.OP_SETUPVAL: /* A B UpValue[B]:= R(A) */ upValues[i>>>23].setValue(stack[a]); continue; - + case Lua.OP_SETTABLE: /* A B C R(A)[RK(B)]:= RK(C) */ - stack[a].set(((b=i>>>23)>0xff? k[b&0x0ff]: stack[b]), (c=(i>>14)&0x1ff)>0xff? k[c&0x0ff]: stack[c]); + stack[a].set((b = i>>>23) > 0xff? k[b & 0x0ff]: stack[b], + (c = i>>14 & 0x1ff) > 0xff? k[c & 0x0ff]: stack[c]); continue; - + case Lua.OP_NEWTABLE: /* A B C R(A):= {} (size = B,C) */ - stack[a] = new LuaTable(i>>>23,(i>>14)&0x1ff); + stack[a] = new LuaTable(i>>>23, i>>14 & 0x1ff); continue; - + case Lua.OP_SELF: /* A B C R(A+1):= R(B): R(A):= R(B)[RK(C)] */ - stack[a+1] = (o = stack[i>>>23]); - stack[a] = o.get((c=(i>>14)&0x1ff)>0xff? k[c&0x0ff]: stack[c]); + stack[a+1] = o = stack[i>>>23]; + stack[a] = o.get((c = i>>14 & 0x1ff) > 0xff? k[c & 0x0ff]: stack[c]); continue; - + case Lua.OP_ADD: /* A B C R(A):= RK(B) + RK(C) */ - stack[a] = ((b=i>>>23)>0xff? k[b&0x0ff]: stack[b]).add((c=(i>>14)&0x1ff)>0xff? k[c&0x0ff]: stack[c]); + stack[a] = ((b = i>>>23) > 0xff? k[b & 0x0ff]: stack[b]) + .add((c = i>>14 & 0x1ff) > 0xff? k[c & 0x0ff]: stack[c]); continue; - + case Lua.OP_SUB: /* A B C R(A):= RK(B) - RK(C) */ - stack[a] = ((b=i>>>23)>0xff? k[b&0x0ff]: stack[b]).sub((c=(i>>14)&0x1ff)>0xff? k[c&0x0ff]: stack[c]); + stack[a] = ((b = i>>>23) > 0xff? k[b & 0x0ff]: stack[b]) + .sub((c = i>>14 & 0x1ff) > 0xff? k[c & 0x0ff]: stack[c]); continue; - + case Lua.OP_MUL: /* A B C R(A):= RK(B) * RK(C) */ - stack[a] = ((b=i>>>23)>0xff? k[b&0x0ff]: stack[b]).mul((c=(i>>14)&0x1ff)>0xff? k[c&0x0ff]: stack[c]); + stack[a] = ((b = i>>>23) > 0xff? k[b & 0x0ff]: stack[b]) + .mul((c = i>>14 & 0x1ff) > 0xff? k[c & 0x0ff]: stack[c]); continue; - + case Lua.OP_DIV: /* A B C R(A):= RK(B) / RK(C) */ - stack[a] = ((b=i>>>23)>0xff? k[b&0x0ff]: stack[b]).div((c=(i>>14)&0x1ff)>0xff? k[c&0x0ff]: stack[c]); + stack[a] = ((b = i>>>23) > 0xff? k[b & 0x0ff]: stack[b]) + .div((c = i>>14 & 0x1ff) > 0xff? k[c & 0x0ff]: stack[c]); continue; - + case Lua.OP_MOD: /* A B C R(A):= RK(B) % RK(C) */ - stack[a] = ((b=i>>>23)>0xff? k[b&0x0ff]: stack[b]).mod((c=(i>>14)&0x1ff)>0xff? k[c&0x0ff]: stack[c]); + stack[a] = ((b = i>>>23) > 0xff? k[b & 0x0ff]: stack[b]) + .mod((c = i>>14 & 0x1ff) > 0xff? k[c & 0x0ff]: stack[c]); continue; - + case Lua.OP_POW: /* A B C R(A):= RK(B) ^ RK(C) */ - stack[a] = ((b=i>>>23)>0xff? k[b&0x0ff]: stack[b]).pow((c=(i>>14)&0x1ff)>0xff? k[c&0x0ff]: stack[c]); + stack[a] = ((b = i>>>23) > 0xff? k[b & 0x0ff]: stack[b]) + .pow((c = i>>14 & 0x1ff) > 0xff? k[c & 0x0ff]: stack[c]); continue; - + case Lua.OP_UNM: /* A B R(A):= -R(B) */ stack[a] = stack[i>>>23].neg(); continue; - + case Lua.OP_NOT: /* A B R(A):= not R(B) */ stack[a] = stack[i>>>23].not(); continue; - + case Lua.OP_LEN: /* A B R(A):= length of R(B) */ stack[a] = stack[i>>>23].len(); continue; - + case Lua.OP_CONCAT: /* A B C R(A):= R(B).. ... ..R(C) */ b = i>>>23; - c = (i>>14)&0x1ff; - { - if ( c > b+1 ) { - Buffer sb = stack[c].buffer(); - while ( --c>=b ) - sb.concatTo(stack[c]); - stack[a] = sb.value(); - } else { - stack[a] = stack[c-1].concat(stack[c]); - } + c = i>>14 & 0x1ff; { + if (c > b+1) { + Buffer sb = stack[c].buffer(); + while ( --c >= b ) + sb.concatTo(stack[c]); + stack[a] = sb.value(); + } else { + stack[a] = stack[c-1].concat(stack[c]); } + } continue; - + case Lua.OP_JMP: /* A sBx pc+=sBx; if (A) close all upvalues >= R(A - 1) */ - pc += (i>>>14)-0x1ffff; + pc += (i>>>14)-0x1ffff; if (a > 0) { - for (--a, b = openups.length; --b>=0; ) + for (--a, b = openups.length; --b >= 0;) if (openups[b] != null && openups[b].index >= a) { openups[b].close(); openups[b] = null; } } continue; - + case Lua.OP_EQ: /* A B C if ((RK(B) == RK(C)) ~= A) then pc++ */ - if ( ((b=i>>>23)>0xff? k[b&0x0ff]: stack[b]).eq_b((c=(i>>14)&0x1ff)>0xff? k[c&0x0ff]: stack[c]) != (a!=0) ) + if (((b = i>>>23) > 0xff? k[b & 0x0ff]: stack[b]) + .eq_b((c = i>>14 & 0x1ff) > 0xff? k[c & 0x0ff]: stack[c]) != (a != 0)) ++pc; continue; - + case Lua.OP_LT: /* A B C if ((RK(B) < RK(C)) ~= A) then pc++ */ - if ( ((b=i>>>23)>0xff? k[b&0x0ff]: stack[b]).lt_b((c=(i>>14)&0x1ff)>0xff? k[c&0x0ff]: stack[c]) != (a!=0) ) + if (((b = i>>>23) > 0xff? k[b & 0x0ff]: stack[b]) + .lt_b((c = i>>14 & 0x1ff) > 0xff? k[c & 0x0ff]: stack[c]) != (a != 0)) ++pc; continue; - + case Lua.OP_LE: /* A B C if ((RK(B) <= RK(C)) ~= A) then pc++ */ - if ( ((b=i>>>23)>0xff? k[b&0x0ff]: stack[b]).lteq_b((c=(i>>14)&0x1ff)>0xff? k[c&0x0ff]: stack[c]) != (a!=0) ) + if (((b = i>>>23) > 0xff? k[b & 0x0ff]: stack[b]) + .lteq_b((c = i>>14 & 0x1ff) > 0xff? k[c & 0x0ff]: stack[c]) != (a != 0)) ++pc; continue; - + case Lua.OP_TEST: /* A C if not (R(A) <=> C) then pc++ */ - if ( stack[a].toboolean() != ((i&(0x1ff<<14))!=0) ) + if (stack[a].toboolean() != ((i & 0x1ff<<14) != 0)) ++pc; continue; - + case Lua.OP_TESTSET: /* A B C if (R(B) <=> C) then R(A):= R(B) else pc++ */ /* note: doc appears to be reversed */ - if ( (o=stack[i>>>23]).toboolean() != ((i&(0x1ff<<14))!=0) ) + if ((o = stack[i>>>23]).toboolean() != ((i & 0x1ff<<14) != 0)) ++pc; else stack[a] = o; // TODO: should be sBx? continue; - + case Lua.OP_CALL: /* A B C R(A), ... ,R(A+C-2):= R(A)(R(A+1), ... ,R(A+B-1)) */ - switch ( i & (Lua.MASK_B | Lua.MASK_C) ) { - case (1<>>23; - c = (i>>14)&0x1ff; - v = stack[a].invoke(b>0? - varargsOf(stack, a+1, b-1): // exact arg count - varargsOf(stack, a+1, top-v.narg()-(a+1), v)); // from prev top - if ( c > 0 ) { + c = i>>14 & 0x1ff; + v = stack[a].invoke(b > 0? varargsOf(stack, a+1, b-1): // exact arg count + varargsOf(stack, a+1, top-v.narg()-(a+1), v)); // from prev top + if (c > 0) { v.copyto(stack, a, c-1); v = NONE; } else { - top = a + v.narg(); + top = a+v.narg(); v = v.dealias(); } continue; } - + case Lua.OP_TAILCALL: /* A B C return R(A)(R(A+1), ... ,R(A+B-1)) */ - switch ( i & Lua.MASK_B ) { - case (1<>>23; - v = b>0? - varargsOf(stack,a+1,b-1): // exact arg count + v = b > 0? varargsOf(stack, a+1, b-1): // exact arg count varargsOf(stack, a+1, top-v.narg()-(a+1), v); // from prev top - return new TailcallVarargs( stack[a], v ); + return new TailcallVarargs(stack[a], v); } - + case Lua.OP_RETURN: /* A B return R(A), ... ,R(A+B-2) (see note) */ b = i>>>23; - switch ( b ) { - case 0: return varargsOf(stack, a, top-v.narg()-a, v); - case 1: return NONE; - case 2: return stack[a]; + switch (b) { + case 0: + return varargsOf(stack, a, top-v.narg()-a, v); + case 1: + return NONE; + case 2: + return stack[a]; default: return varargsOf(stack, a, b-1); } - + case Lua.OP_FORLOOP: /* A sBx R(A)+=R(A+2): if R(A) >>14)-0x1ffff; - } - } - continue; - - case Lua.OP_FORPREP: /* A sBx R(A)-=R(A+2): pc+=sBx */ - { - LuaValue init = stack[a].checknumber("'for' initial value must be a number"); - LuaValue limit = stack[a + 1].checknumber("'for' limit must be a number"); - LuaValue step = stack[a + 2].checknumber("'for' step must be a number"); - stack[a] = init.sub(step); - stack[a + 1] = limit; - stack[a + 2] = step; + { + LuaValue limit = stack[a+1]; + LuaValue step = stack[a+2]; + LuaValue idx = stack[a].add(step); + if (step.gt_b(0)? idx.lteq_b(limit): idx.gteq_b(limit)) { + stack[a] = idx; + stack[a+3] = idx; pc += (i>>>14)-0x1ffff; } + } + continue; + + case Lua.OP_FORPREP: /* A sBx R(A)-=R(A+2): pc+=sBx */ + { + LuaValue init = stack[a].checknumber("'for' initial value must be a number"); + LuaValue limit = stack[a+1].checknumber("'for' limit must be a number"); + LuaValue step = stack[a+2].checknumber("'for' step must be a number"); + stack[a] = init.sub(step); + stack[a+1] = limit; + stack[a+2] = step; + pc += (i>>>14)-0x1ffff; + } continue; case Lua.OP_TFORCALL: /* A C R(A+3), ... ,R(A+2+C) := R(A)(R(A+1), R(A+2)); */ - v = stack[a].invoke(varargsOf(stack[a+1],stack[a+2])); - c = (i>>14) & 0x1ff; - while (--c >= 0) + v = stack[a].invoke(varargsOf(stack[a+1], stack[a+2])); + c = i>>14 & 0x1ff; + while ( --c >= 0 ) stack[a+3+c] = v.arg(c+1); v = NONE; continue; case Lua.OP_TFORLOOP: /* A sBx if R(A+1) ~= nil then { R(A)=R(A+1); pc += sBx */ if (!stack[a+1].isnil()) { /* continue loop? */ - stack[a] = stack[a+1]; /* save control varible. */ + stack[a] = stack[a+1]; /* save control varible. */ pc += (i>>>14)-0x1ffff; } continue; - + case Lua.OP_SETLIST: /* A B C R(A)[(C-1)*FPF+i]:= R(A+i), 1 <= i <= B */ - { - if ( (c=(i>>14)&0x1ff) == 0 ) - c = code[++pc]; - int offset = (c-1) * Lua.LFIELDS_PER_FLUSH; - o = stack[a]; - if ( (b=i>>>23) == 0 ) { - b = top - a - 1; - int m = b - v.narg(); - int j=1; - for ( ;j<=m; j++ ) - o.set(offset+j, stack[a + j]); - for ( ;j<=b; j++ ) - o.set(offset+j, v.arg(j-m)); - } else { - o.presize( offset + b ); - for (int j=1; j<=b; j++) - o.set(offset+j, stack[a + j]); - } + { + if ((c = i>>14 & 0x1ff) == 0) + c = code[++pc]; + int offset = (c-1)*Lua.LFIELDS_PER_FLUSH; + o = stack[a]; + if ((b = i>>>23) == 0) { + b = top-a-1; + int m = b-v.narg(); + int j = 1; + for (; j <= m; j++) + o.set(offset+j, stack[a+j]); + for (; j <= b; j++) + o.set(offset+j, v.arg(j-m)); + } else { + o.presize(offset+b); + for (int j = 1; j <= b; j++) + o.set(offset+j, stack[a+j]); } + } continue; - + case Lua.OP_CLOSURE: /* A Bx R(A):= closure(KPROTO[Bx]) */ - { - Prototype newp = p.p[i>>>14]; - LuaClosure ncl = new LuaClosure(newp, globals); - Upvaldesc[] uv = newp.upvalues; - for ( int j=0, nup=uv.length; j>>14]; + LuaClosure ncl = new LuaClosure(newp, globals); + Upvaldesc[] uv = newp.upvalues; + for (int j = 0, nup = uv.length; j < nup; ++j) { + if (uv[j].instack) /* upvalue refes to local variable? */ + ncl.upValues[j] = findupval(stack, uv[j].idx, openups); + else /* get upvalue from enclosing function */ + ncl.upValues[j] = upValues[uv[j].idx]; } + stack[a] = ncl; + } continue; - + case Lua.OP_VARARG: /* A B R(A), R(A+1), ..., R(A+B-1) = vararg */ b = i>>>23; - if ( b == 0 ) { - top = a + (b = varargs.narg()); + if (b == 0) { + top = a+(b = varargs.narg()); v = varargs; } else { - for ( int j=1; j=0; ) - if ( openups[u] != null ) + if (openups != null) + for (int u = openups.length; --u >= 0;) + if (openups[u] != null) openups[u].close(); if (globals != null && globals.debuglib != null) globals.debuglib.onReturn(); @@ -527,21 +609,21 @@ public class LuaClosure extends LuaFunction { } /** - * Run the error hook if there is one - * @param msg the message to use in error hook processing. - * */ + * Run the error hook if there is one + * + * @param msg the message to use in error hook processing. + */ String errorHook(String msg, int level) { - if (globals == null ) return msg; + if (globals == null) + return msg; final LuaThread r = globals.running; if (r.errorfunc == null) - return globals.debuglib != null? - msg + "\n" + globals.debuglib.traceback(level): - msg; + return globals.debuglib != null? msg + "\n" + globals.debuglib.traceback(level): msg; final LuaValue e = r.errorfunc; r.errorfunc = null; try { - return e.call( LuaValue.valueOf(msg) ).tojstring(); - } catch ( Throwable t ) { + return e.call(LuaValue.valueOf(msg)).tojstring(); + } catch (Throwable t) { return "error in error handling"; } finally { r.errorfunc = e; @@ -557,19 +639,19 @@ public class LuaClosure extends LuaFunction { frame = globals.debuglib.getCallFrame(le.level); if (frame != null) { String src = frame.shortsource(); - file = src != null ? src : "?"; + file = src != null? src: "?"; line = frame.currentline(); } } if (frame == null) { file = p.source != null? p.source.tojstring(): "?"; - line = p.lineinfo != null && pc >= 0 && pc < p.lineinfo.length ? p.lineinfo[pc] : -1; + line = p.lineinfo != null && pc >= 0 && pc < p.lineinfo.length? p.lineinfo[pc]: -1; } } - le.fileline = file + ":" + line; + le.fileline = file + ": " + line; le.traceback = errorHook(le.getMessage(), le.level); } - + private UpValue findupval(LuaValue[] stack, short idx, UpValue[] openups) { final int n = openups.length; for (int i = 0; i < n; ++i) @@ -585,14 +667,14 @@ public class LuaClosure extends LuaFunction { protected LuaValue getUpvalue(int i) { return upValues[i].getValue(); } - + protected void setUpvalue(int i, LuaValue v) { upValues[i].setValue(v); } + @Override public String name() { - return "<"+p.shortsource()+":"+p.linedefined+">"; + return "<" + p.shortsource() + ":" + p.linedefined + ">"; } - - + } diff --git a/src/core/org/luaj/vm2/LuaDouble.java b/luaj-core/src/main/java/org/luaj/vm2/LuaDouble.java similarity index 94% rename from src/core/org/luaj/vm2/LuaDouble.java rename to luaj-core/src/main/java/org/luaj/vm2/LuaDouble.java index 0c5cdd66..c23e7849 100644 --- a/src/core/org/luaj/vm2/LuaDouble.java +++ b/luaj-core/src/main/java/org/luaj/vm2/LuaDouble.java @@ -21,6 +21,7 @@ ******************************************************************************/ package org.luaj.vm2; +import org.luaj.vm2.compat.JavaCompat; import org.luaj.vm2.lib.MathLib; /** @@ -33,9 +34,9 @@ import org.luaj.vm2.lib.MathLib; *

* Almost all API's implemented in LuaDouble are defined and documented in {@link LuaValue}. *

- * However the constants {@link #NAN}, {@link #POSINF}, {@link #NEGINF}, - * {@link #JSTR_NAN}, {@link #JSTR_POSINF}, and {@link #JSTR_NEGINF} may be useful - * when dealing with Nan or Infinite values. + * However the constants {@link #NAN}, {@link #NEGNAN}, {@link #POSINF}, {@link #NEGINF}, + * {@link #JSTR_NAN}, {@link #JSTR_NEGNAN}, {@link #JSTR_POSINF}, and {@link #JSTR_NEGINF} may be useful + * when dealing with Nan or Infinite values. *

* LuaDouble also defines functions for handling the unique math rules of lua devision and modulo in *