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/luaj-core/src/main/java/org/luaj/vm2/Buffer.java b/luaj-core/src/main/java/org/luaj/vm2/Buffer.java index a54d4d89..ba393bcb 100644 --- a/luaj-core/src/main/java/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 @@ -30,7 +30,7 @@ package org.luaj.vm2; *

* To convert back to a {@link LuaValue} again, the function * {@link Buffer#value()} is used. - * + * * @see LuaValue * @see LuaValue#buffer() * @see LuaString @@ -57,7 +57,7 @@ public final class Buffer { /** * Create buffer with default capacity - * + * * @see #DEFAULT_CAPACITY */ public Buffer() { @@ -66,7 +66,7 @@ public final class Buffer { /** * Create buffer with specified initial capacity - * + * * @param initialCapacity the initial capacity */ public Buffer(int initialCapacity) { @@ -78,7 +78,7 @@ public final class Buffer { /** * Create buffer with specified initial value - * + * * @param value the initial value */ public Buffer(LuaValue value) { @@ -89,7 +89,7 @@ public final class Buffer { /** * Get buffer contents as a {@link LuaValue} - * + * * @return value as a {@link LuaValue}, converting as necessary */ public LuaValue value() { @@ -98,7 +98,7 @@ public final class Buffer { /** * Set buffer contents as a {@link LuaValue} - * + * * @param value value to set */ public Buffer setvalue(LuaValue value) { @@ -110,17 +110,17 @@ public final class Buffer { /** * Convert the buffer to a {@link LuaString} - * + * * @return the value as a {@link LuaString} */ - public final LuaString tostring() { + 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() { @@ -129,19 +129,20 @@ public final class Buffer { /** * 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) { + public Buffer append(byte b) { makeroom(0, 1); bytes[offset+length++] = b; return this; @@ -149,20 +150,20 @@ public final class Buffer { /** * Append a {@link LuaValue} to the buffer. - * + * * @return {@code this} to allow call chaining */ - public final Buffer append(LuaValue val) { + 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); @@ -173,11 +174,11 @@ public final class Buffer { /** * 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); @@ -188,7 +189,7 @@ public final class Buffer { /** * 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. @@ -199,7 +200,7 @@ public final class Buffer { /** * 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. @@ -212,7 +213,7 @@ public final class Buffer { * 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} * @return {@link Buffer} for use in call chaining. @@ -223,7 +224,7 @@ public final class Buffer { /** * 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. @@ -240,13 +241,13 @@ public final class Buffer { /** * 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) { + public void makeroom(int nbefore, int nafter) { if (value != null) { LuaString s = value.strvalue(); value = null; @@ -263,11 +264,11 @@ public final class Buffer { /** * Reallocate the internal storage for the buffer - * + * * @param newSize the size of the buffer to use * @param newOffset the offset to use */ - private final void realloc(int newSize, int newOffset) { + private void realloc(int newSize, int newOffset) { if (newSize != bytes.length) { byte[] newBytes = new byte[newSize]; System.arraycopy(bytes, offset, newBytes, newOffset, length); diff --git a/luaj-core/src/main/java/org/luaj/vm2/Globals.java b/luaj-core/src/main/java/org/luaj/vm2/Globals.java index a7705988..f73087b4 100644 --- a/luaj-core/src/main/java/org/luaj/vm2/Globals.java +++ b/luaj-core/src/main/java/org/luaj/vm2/Globals.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 @@ -36,13 +36,13 @@ import org.luaj.vm2.lib.ResourceFinder; * Global environment used by luaj. Contains global variables referenced by * executing lua. *

- * + * *

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
@@ -50,12 +50,12 @@ import org.luaj.vm2.lib.ResourceFinder;
  * 	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
@@ -63,17 +63,17 @@ import org.luaj.vm2.lib.ResourceFinder;
  * 	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(); 
+ * 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 * - * + * *

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 @@ -116,13 +116,13 @@ import org.luaj.vm2.lib.ResourceFinder; *
  • "_G" Pointer to this Globals. *
  • "_VERSION" String containing the version of luaj. * - * + * *

    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 @@ -195,27 +195,28 @@ public class Globals extends LuaTable { * 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 */ public Loader loader; /** * The installed compiler. - * + * * @see Compiler */ public Compiler compiler; /** * The installed undumper. - * + * * @see Undumper */ public Undumper undumper; @@ -223,7 +224,7 @@ public class Globals extends LuaTable { /** * 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. @@ -239,7 +240,7 @@ public class Globals extends LuaTable { /** * 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. @@ -254,7 +255,7 @@ public class Globals extends LuaTable { /** * 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. @@ -267,7 +268,7 @@ public class Globals extends LuaTable { /** * 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. @@ -285,7 +286,7 @@ public class Globals extends LuaTable { * 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. @@ -302,7 +303,7 @@ public class Globals extends LuaTable { * 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. @@ -318,7 +319,7 @@ public class Globals extends LuaTable { /** * 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 @@ -342,7 +343,7 @@ public class Globals extends LuaTable { * 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 @@ -391,7 +392,7 @@ public class Globals extends LuaTable { /** * 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 @@ -415,14 +416,17 @@ public class Globals extends LuaTable { n = s.length(); } + @Override public void close() throws IOException { i = n; } + @Override public int read() throws IOException { 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) @@ -444,15 +448,18 @@ public class Globals extends LuaTable { 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) @@ -463,12 +470,14 @@ public class Globals extends LuaTable { return n_read; } + @Override public long skip(long n) throws IOException { final long k = Math.min(n, j-i); i += k; return k; } + @Override public int available() throws IOException { return j-i; } @@ -488,6 +497,7 @@ public class Globals extends LuaTable { this.r = r; } + @Override protected int avail() throws IOException { if (i < j) return j-i; @@ -505,6 +515,7 @@ public class Globals extends LuaTable { return j; } + @Override public void close() throws IOException { r.close(); } @@ -529,6 +540,7 @@ public class Globals extends LuaTable { this.s = s; } + @Override protected int avail() throws IOException { if (i < j) return j-i; @@ -549,10 +561,12 @@ public class Globals extends LuaTable { 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; @@ -563,10 +577,12 @@ public class Globals extends LuaTable { } } + @Override public boolean markSupported() { return true; } + @Override public synchronized void reset() throws IOException { i = 0; } diff --git a/luaj-core/src/main/java/org/luaj/vm2/LoadState.java b/luaj-core/src/main/java/org/luaj/vm2/LoadState.java index c8624556..3dd25cff 100644 --- a/luaj-core/src/main/java/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 @@ -35,7 +35,7 @@ import java.io.InputStream; *

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

      * {
      * 	@code
    @@ -44,7 +44,7 @@ import java.io.InputStream;
      * 	chunk.call();
      * }
      * 
    - * + * * This should work regardless of which {@link Globals.Compiler} or * {@link Globals.Undumper} have been installed. *

    @@ -53,10 +53,10 @@ import java.io.InputStream; * {@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
    @@ -67,10 +67,10 @@ import java.io.InputStream;
      * 	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");
    @@ -78,10 +78,10 @@ import java.io.InputStream;
     * c.call();
     * }
      * 
    - * - * + * + * * More commonly, the {@link Globals.Undumper} may be used to undump them: - * + * *
      * {
      * 	@code
    @@ -90,7 +90,7 @@ import java.io.InputStream;
      * 	c.call();
      * }
      * 
    - * + * * @see Globals.Compiler * @see Globals.Undumper * @see LuaClosure @@ -124,8 +124,8 @@ public class LoadState { 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_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; @@ -196,18 +196,18 @@ public class LoadState { /** * 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]); + 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 - * + * * @return the array of int values laoded. **/ int[] loadIntArray() throws IOException { @@ -222,16 +222,15 @@ public class LoadState { is.readFully(buf, 0, m); int[] array = new int[n]; for (int i = 0, j = 0; i < n; ++i, j += 4) - array[i] = luacLittleEndian - ? (buf[j+3]<<24) | ((0xff & buf[j+2])<<16) | ((0xff & buf[j+1])<<8) | (0xff & buf[j+0]) - : (buf[j+0]<<24) | ((0xff & buf[j+1])<<16) | ((0xff & buf[j+2])<<8) | (0xff & buf[j+3]); + array[i] = luacLittleEndian? buf[j+3]<<24 | (0xff & buf[j+2])<<16 | (0xff & buf[j+1])<<8 | 0xff & buf[j+0] + : buf[j+0]<<24 | (0xff & buf[j+1])<<16 | (0xff & buf[j+2])<<8 | 0xff & buf[j+3]; return array; } /** * Load a long value from the input stream - * + * * @return the long value laoded. **/ long loadInt64() throws IOException { @@ -243,12 +242,12 @@ public class LoadState { b = loadInt(); a = loadInt(); } - return (((long) b)<<32) | (((long) a) & 0xffffffffL); + return (long) b<<32 | a & 0xffffffffL; } /** * Load a lua strin gvalue from the input stream - * + * * @return the {@link LuaString} value laoded. **/ LuaString loadString() throws IOException { @@ -262,25 +261,25 @@ public class LoadState { /** * Convert bits in a long value to a {@link LuaValue}. - * + * * @param bits long value containing the bits * @return {@link LuaInteger} or {@link LuaDouble} whose value corresponds * to the bits provided. */ public static LuaValue longBitsToLuaNumber(long bits) { - if ((bits & ((1L<<63)-1)) == 0L) { + if ((bits & (1L<<63)-1) == 0L) { return LuaValue.ZERO; } - int e = (int) ((bits>>52) & 0x7ffL)-1023; + 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<>63) != 0)? -intValue: intValue); + int intValue = (int) (f>>shift) | 1<>63 != 0? -intValue: intValue); } } @@ -289,7 +288,7 @@ public class LoadState { /** * Load a number from a binary chunk - * + * * @return the {@link LuaValue} loaded * @throws IOException if an i/o exception occurs */ @@ -303,7 +302,7 @@ public class LoadState { /** * Load a list of constants from a binary chunk - * + * * @param f the function prototype * @throws IOException if an i/o exception occurs */ @@ -316,7 +315,7 @@ public class LoadState { 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()); @@ -345,14 +344,14 @@ public class LoadState { f.upvalues = n > 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 */ @@ -375,7 +374,7 @@ public class LoadState { /** * Load a function prototype from the input stream - * + * * @param p name of the source * @return {@link Prototype} instance that was loaded * @throws IOException @@ -406,13 +405,13 @@ public class LoadState { /** * Load the lua chunk header values. - * + * * @throws IOException if an i/o exception occurs. */ public void loadHeader() throws IOException { luacVersion = is.readByte(); luacFormat = is.readByte(); - luacLittleEndian = (0 != is.readByte()); + luacLittleEndian = 0 != is.readByte(); luacSizeofInt = is.readByte(); luacSizeofSizeT = is.readByte(); luacSizeofInstruction = is.readByte(); @@ -426,7 +425,7 @@ public class LoadState { /** * Load input stream as a lua binary chunk if the first 4 bytes are the lua * binary signature. - * + * * @param stream InputStream to read, after having read the first byte * already * @param chunkname Name to apply to the loaded chunk @@ -459,7 +458,7 @@ public class LoadState { /** * Construct a source name from a supplied chunk name - * + * * @param name String name that appears in the chunk * @return source file name */ @@ -479,6 +478,7 @@ public class LoadState { } private static final class GlobalsUndumper implements Globals.Undumper { + @Override public Prototype undump(InputStream stream, String chunkname) throws IOException { return LoadState.undump(stream, chunkname); } diff --git a/luaj-core/src/main/java/org/luaj/vm2/LocVars.java b/luaj-core/src/main/java/org/luaj/vm2/LocVars.java index bb97b797..035d6224 100644 --- a/luaj-core/src/main/java/org/luaj/vm2/LocVars.java +++ b/luaj-core/src/main/java/org/luaj/vm2/LocVars.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 @@ -37,7 +37,7 @@ public class LocVars { /** * Construct a LocVars instance. - * + * * @param varname The local variable name * @param startpc The instruction offset when the variable comes into scope * @param endpc The instruction offset when the variable goes out of scope diff --git a/luaj-core/src/main/java/org/luaj/vm2/Lua.java b/luaj-core/src/main/java/org/luaj/vm2/Lua.java index 81a4e9e6..2773e22b 100644 --- a/luaj-core/src/main/java/org/luaj/vm2/Lua.java +++ b/luaj-core/src/main/java/org/luaj/vm2/Lua.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 @@ -64,33 +64,33 @@ public class Lua { */ 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_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_Ax = SIZE_C+SIZE_B+SIZE_A; 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_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; } /* @@ -134,23 +134,23 @@ public class Lua { */ /** this bit 1 means constant (0 means register) */ - public static final int BITRK = (1<<(SIZE_B-1)); + public static final int BITRK = 1<>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 */ diff --git a/luaj-core/src/main/java/org/luaj/vm2/LuaBoolean.java b/luaj-core/src/main/java/org/luaj/vm2/LuaBoolean.java index e0a40415..fe50a61f 100644 --- a/luaj-core/src/main/java/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 @@ -33,7 +33,7 @@ package org.luaj.vm2; * Any {@link LuaValue} can be converted to its equivalent boolean * representation using {@link LuaValue#toboolean()} *

    - * + * * @see LuaValue * @see LuaValue#valueOf(boolean) * @see LuaValue#TRUE @@ -57,47 +57,56 @@ 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 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"; } + @Override public boolean optboolean(boolean defval) { return this.v; } + @Override public boolean checkboolean() { return v; } + @Override public LuaValue getmetatable() { return s_metatable; } diff --git a/luaj-core/src/main/java/org/luaj/vm2/LuaClosure.java b/luaj-core/src/main/java/org/luaj/vm2/LuaClosure.java index aa3ac55b..5354246c 100644 --- a/luaj-core/src/main/java/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 @@ -30,7 +30,7 @@ import org.luaj.vm2.lib.DebugLib.CallFrame; * {@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: *

      @@ -43,7 +43,7 @@ import org.luaj.vm2.lib.DebugLib.CallFrame; *

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

        * {
        * 	@code
      @@ -58,7 +58,7 @@ import org.luaj.vm2.lib.DebugLib.CallFrame;
        * 

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

        * {
        * 	@code
      @@ -87,7 +87,7 @@ import org.luaj.vm2.lib.DebugLib.CallFrame;
        * 
    • {@link LuaValue#invokemethod(String,Varargs)}
    • *
    • ...
    • *
    - * + * * @see LuaValue * @see LuaFunction * @see LuaValue#isclosure() @@ -97,7 +97,7 @@ 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; @@ -109,7 +109,7 @@ public class LuaClosure extends LuaFunction { * 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. */ @@ -119,6 +119,7 @@ public class LuaClosure extends LuaFunction { globals = env instanceof Globals? (Globals) env: null; } + @Override public void initupvalue1(LuaValue env) { if (p.upvalues == null || p.upvalues.length == 0) this.upValues = NOUPVALUES; @@ -128,18 +129,22 @@ public class LuaClosure extends LuaFunction { } } + @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(); } @@ -151,11 +156,13 @@ public class LuaClosure extends LuaFunction { return stack; } + @Override public final LuaValue call() { LuaValue[] stack = getNewStack(); return execute(stack, NONE).arg1(); } + @Override public final LuaValue call(LuaValue arg) { LuaValue[] stack = getNewStack(); switch (p.numparams) { @@ -167,6 +174,7 @@ public class LuaClosure extends LuaFunction { } } + @Override public final LuaValue call(LuaValue arg1, LuaValue arg2) { LuaValue[] stack = getNewStack(); switch (p.numparams) { @@ -182,6 +190,7 @@ public class LuaClosure extends LuaFunction { } } + @Override public final LuaValue call(LuaValue arg1, LuaValue arg2, LuaValue arg3) { LuaValue[] stack = getNewStack(); switch (p.numparams) { @@ -202,10 +211,12 @@ public class LuaClosure extends LuaFunction { } } + @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; i < p.numparams; i++) @@ -237,7 +248,7 @@ public class LuaClosure extends LuaFunction { // pull out instruction i = code[pc]; - a = ((i>>6) & 0xff); + a = i>>6 & 0xff; // process the op code switch (i & 0x3f) { @@ -262,8 +273,8 @@ public class LuaClosure extends LuaFunction { 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) + stack[a] = i>>>23 != 0? LuaValue.TRUE: LuaValue.FALSE; + if ((i & 0x1ff<<14) != 0) ++pc; /* skip next instruction (if C) */ continue; @@ -277,16 +288,16 @@ public class LuaClosure extends LuaFunction { 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) */ @@ -294,47 +305,47 @@ public class LuaClosure extends LuaFunction { 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]); + .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]); + .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]); + .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]); + .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]); + .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]); + .pow((c = i>>14 & 0x1ff) > 0xff? k[c & 0x0ff]: stack[c]); continue; case Lua.OP_UNM: /* A B R(A):= -R(B) */ @@ -351,7 +362,7 @@ public class LuaClosure extends LuaFunction { case Lua.OP_CONCAT: /* A B C R(A):= R(B).. ... ..R(C) */ b = i>>>23; - c = (i>>14) & 0x1ff; { + c = i>>14 & 0x1ff; { if (c > b+1) { Buffer sb = stack[c].buffer(); while ( --c >= b ) @@ -376,30 +387,30 @@ public class LuaClosure extends LuaFunction { 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)) + .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)) + .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)) + .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? @@ -407,41 +418,41 @@ public class LuaClosure extends LuaFunction { 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; + 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) { @@ -456,13 +467,13 @@ public class LuaClosure extends LuaFunction { 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; @@ -511,7 +522,7 @@ public class LuaClosure extends LuaFunction { 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; + c = i>>14 & 0x1ff; while ( --c >= 0 ) stack[a+3+c] = v.arg(c+1); v = NONE; @@ -526,7 +537,7 @@ public class LuaClosure extends LuaFunction { 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) + if ((c = i>>14 & 0x1ff) == 0) c = code[++pc]; int offset = (c-1)*Lua.LFIELDS_PER_FLUSH; o = stack[a]; @@ -599,7 +610,7 @@ public class LuaClosure extends LuaFunction { /** * Run the error hook if there is one - * + * * @param msg the message to use in error hook processing. */ String errorHook(String msg, int level) { @@ -661,6 +672,7 @@ public class LuaClosure extends LuaFunction { upValues[i].setValue(v); } + @Override public String name() { return "<" + p.shortsource() + ":" + p.linedefined + ">"; } diff --git a/luaj-core/src/main/java/org/luaj/vm2/LuaDouble.java b/luaj-core/src/main/java/org/luaj/vm2/LuaDouble.java index 0f801031..23661fe7 100644 --- a/luaj-core/src/main/java/org/luaj/vm2/LuaDouble.java +++ b/luaj-core/src/main/java/org/luaj/vm2/LuaDouble.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 @@ -48,7 +48,7 @@ import org.luaj.vm2.lib.MathLib; *
  • {@link #dmod_d(double, double)}
  • * *

    - * + * * @see LuaValue * @see LuaNumber * @see LuaInteger @@ -88,106 +88,149 @@ public class LuaDouble extends LuaNumber { this.v = d; } + @Override public int hashCode() { long l = Double.doubleToLongBits(v+1); - return ((int) (l>>32))+(int) l; + return (int) (l>>32)+(int) l; } + @Override public boolean islong() { return v == (long) v; } + @Override public byte tobyte() { return (byte) (long) v; } + @Override public char tochar() { return (char) (long) v; } + @Override public double todouble() { return v; } + @Override public float tofloat() { return (float) v; } + @Override public int toint() { return (int) (long) v; } + @Override public long tolong() { return (long) v; } + @Override public short toshort() { return (short) (long) v; } + @Override public double optdouble(double defval) { return v; } + @Override public int optint(int defval) { return (int) (long) v; } + @Override public LuaInteger optinteger(LuaInteger defval) { return LuaInteger.valueOf((int) (long) v); } + @Override public long optlong(long defval) { return (long) v; } + @Override public LuaInteger checkinteger() { return LuaInteger.valueOf((int) (long) v); } // unary operators + @Override public LuaValue neg() { return valueOf(-v); } // object equality, used for key comparison + @Override public boolean equals(Object o) { return o instanceof LuaDouble? ((LuaDouble) o).v == v: false; } // equality w/ metatable processing + @Override public LuaValue eq(LuaValue val) { return val.raweq(v)? TRUE: FALSE; } + @Override public boolean eq_b(LuaValue val) { return val.raweq(v); } // equality w/o metatable processing + @Override public boolean raweq(LuaValue val) { return val.raweq(v); } + @Override public boolean raweq(double val) { return v == val; } + @Override public boolean raweq(int val) { return v == val; } // basic binary arithmetic + @Override public LuaValue add(LuaValue rhs) { return rhs.add(v); } + @Override public LuaValue add(double lhs) { return LuaDouble.valueOf(lhs+v); } + @Override public LuaValue sub(LuaValue rhs) { return rhs.subFrom(v); } + @Override public LuaValue sub(double rhs) { return LuaDouble.valueOf(v-rhs); } + @Override public LuaValue sub(int rhs) { return LuaDouble.valueOf(v-rhs); } + @Override public LuaValue subFrom(double lhs) { return LuaDouble.valueOf(lhs-v); } + @Override public LuaValue mul(LuaValue rhs) { return rhs.mul(v); } + @Override public LuaValue mul(double lhs) { return LuaDouble.valueOf(lhs*v); } + @Override public LuaValue mul(int lhs) { return LuaDouble.valueOf(lhs*v); } + @Override public LuaValue pow(LuaValue rhs) { return rhs.powWith(v); } + @Override public LuaValue pow(double rhs) { return MathLib.dpow(v, rhs); } + @Override public LuaValue pow(int rhs) { return MathLib.dpow(v, rhs); } + @Override public LuaValue powWith(double lhs) { return MathLib.dpow(lhs, v); } + @Override public LuaValue powWith(int lhs) { return MathLib.dpow(lhs, v); } + @Override public LuaValue div(LuaValue rhs) { return rhs.divInto(v); } + @Override public LuaValue div(double rhs) { return LuaDouble.ddiv(v, rhs); } + @Override public LuaValue div(int rhs) { return LuaDouble.ddiv(v, rhs); } + @Override public LuaValue divInto(double lhs) { return LuaDouble.ddiv(lhs, v); } + @Override public LuaValue mod(LuaValue rhs) { return rhs.modFrom(v); } + @Override public LuaValue mod(double rhs) { return LuaDouble.dmod(v, rhs); } + @Override public LuaValue mod(int rhs) { return LuaDouble.dmod(v, rhs); } + @Override public LuaValue modFrom(double lhs) { return LuaDouble.dmod(lhs, v); } /** * Divide two double numbers according to lua math, and return a * {@link LuaValue} result. - * + * * @param lhs Left-hand-side of the division. * @param rhs Right-hand-side of the division. * @return {@link LuaValue} for the result of the division, taking into @@ -201,7 +244,7 @@ public class LuaDouble extends LuaNumber { /** * Divide two double numbers according to lua math, and return a double * result. - * + * * @param lhs Left-hand-side of the division. * @param rhs Right-hand-side of the division. * @return Value of the division, taking into account positive and negative @@ -215,7 +258,7 @@ public class LuaDouble extends LuaNumber { /** * Take modulo double numbers according to lua math, and return a * {@link LuaValue} result. - * + * * @param lhs Left-hand-side of the modulo. * @param rhs Right-hand-side of the modulo. * @return {@link LuaValue} for the result of the modulo, using lua's rules @@ -237,7 +280,7 @@ public class LuaDouble extends LuaNumber { /** * Take modulo for double numbers according to lua math, and return a double * result. - * + * * @param lhs Left-hand-side of the modulo. * @param rhs Right-hand-side of the modulo. * @return double value for the result of the modulo, using lua's rules for @@ -257,61 +300,87 @@ public class LuaDouble extends LuaNumber { } // relational operators - public LuaValue lt(LuaValue rhs) { return rhs instanceof LuaNumber? (rhs.gt_b(v)? TRUE: FALSE): super.lt(rhs); } + @Override + public LuaValue lt(LuaValue rhs) { return rhs instanceof LuaNumber? rhs.gt_b(v)? TRUE: FALSE: super.lt(rhs); } + @Override public LuaValue lt(double rhs) { return v < rhs? TRUE: FALSE; } + @Override public LuaValue lt(int rhs) { return v < rhs? TRUE: FALSE; } + @Override public boolean lt_b(LuaValue rhs) { return rhs instanceof LuaNumber? rhs.gt_b(v): super.lt_b(rhs); } + @Override public boolean lt_b(int rhs) { return v < rhs; } + @Override public boolean lt_b(double rhs) { return v < rhs; } + @Override public LuaValue lteq(LuaValue rhs) { - return rhs instanceof LuaNumber? (rhs.gteq_b(v)? TRUE: FALSE): super.lteq(rhs); + return rhs instanceof LuaNumber? rhs.gteq_b(v)? TRUE: FALSE: super.lteq(rhs); } + @Override public LuaValue lteq(double rhs) { return v <= rhs? TRUE: FALSE; } + @Override public LuaValue lteq(int rhs) { return v <= rhs? TRUE: FALSE; } + @Override public boolean lteq_b(LuaValue rhs) { return rhs instanceof LuaNumber? rhs.gteq_b(v): super.lteq_b(rhs); } + @Override public boolean lteq_b(int rhs) { return v <= rhs; } + @Override public boolean lteq_b(double rhs) { return v <= rhs; } - public LuaValue gt(LuaValue rhs) { return rhs instanceof LuaNumber? (rhs.lt_b(v)? TRUE: FALSE): super.gt(rhs); } + @Override + public LuaValue gt(LuaValue rhs) { return rhs instanceof LuaNumber? rhs.lt_b(v)? TRUE: FALSE: super.gt(rhs); } + @Override public LuaValue gt(double rhs) { return v > rhs? TRUE: FALSE; } + @Override public LuaValue gt(int rhs) { return v > rhs? TRUE: FALSE; } + @Override public boolean gt_b(LuaValue rhs) { return rhs instanceof LuaNumber? rhs.lt_b(v): super.gt_b(rhs); } + @Override public boolean gt_b(int rhs) { return v > rhs; } + @Override public boolean gt_b(double rhs) { return v > rhs; } + @Override public LuaValue gteq(LuaValue rhs) { - return rhs instanceof LuaNumber? (rhs.lteq_b(v)? TRUE: FALSE): super.gteq(rhs); + return rhs instanceof LuaNumber? rhs.lteq_b(v)? TRUE: FALSE: super.gteq(rhs); } + @Override public LuaValue gteq(double rhs) { return v >= rhs? TRUE: FALSE; } + @Override public LuaValue gteq(int rhs) { return v >= rhs? TRUE: FALSE; } + @Override public boolean gteq_b(LuaValue rhs) { return rhs instanceof LuaNumber? rhs.lteq_b(v): super.gteq_b(rhs); } + @Override public boolean gteq_b(int rhs) { return v >= rhs; } + @Override public boolean gteq_b(double rhs) { return v >= rhs; } // string comparison + @Override public int strcmp(LuaString rhs) { typerror("attempt to compare number with string"); return 0; } + @Override public String tojstring() { /* if ( v == 0.0 ) { // never occurs in J2me @@ -325,58 +394,73 @@ public class LuaDouble extends LuaNumber { if (Double.isNaN(v)) return JSTR_NAN; if (Double.isInfinite(v)) - return (v < 0? JSTR_NEGINF: JSTR_POSINF); + return v < 0? JSTR_NEGINF: JSTR_POSINF; return Float.toString((float) v); } + @Override public LuaString strvalue() { return LuaString.valueOf(tojstring()); } + @Override public LuaString optstring(LuaString defval) { return LuaString.valueOf(tojstring()); } + @Override public LuaValue tostring() { return LuaString.valueOf(tojstring()); } + @Override public String optjstring(String defval) { return tojstring(); } + @Override public LuaNumber optnumber(LuaNumber defval) { return this; } + @Override public boolean isnumber() { return true; } + @Override public boolean isstring() { return true; } + @Override public LuaValue tonumber() { return this; } + @Override public int checkint() { return (int) (long) v; } + @Override public long checklong() { return (long) v; } + @Override public LuaNumber checknumber() { return this; } + @Override public double checkdouble() { return v; } + @Override public String checkjstring() { return tojstring(); } + @Override public LuaString checkstring() { return LuaString.valueOf(tojstring()); } + @Override public boolean isvalidkey() { return !Double.isNaN(v); } diff --git a/luaj-core/src/main/java/org/luaj/vm2/LuaError.java b/luaj-core/src/main/java/org/luaj/vm2/LuaError.java index dffe6636..b24f4a98 100644 --- a/luaj-core/src/main/java/org/luaj/vm2/LuaError.java +++ b/luaj-core/src/main/java/org/luaj/vm2/LuaError.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 @@ -54,6 +54,7 @@ public class LuaError extends RuntimeException { * Get the string message if it was supplied, or a string representation of * the message object if that was supplied. */ + @Override public String getMessage() { if (traceback != null) return traceback; @@ -68,7 +69,7 @@ public class LuaError extends RuntimeException { /** * Get the LuaValue that was provided in the constructor, or a LuaString * containing the message if it was a string error argument. - * + * * @return LuaValue which was used in the constructor, or a LuaString * containing the message. */ @@ -83,7 +84,7 @@ public class LuaError extends RuntimeException { * Construct LuaError when a program exception occurs. *

    * All errors generated from lua code should throw LuaError(String) instead. - * + * * @param cause the Throwable that caused the error, if known. */ public LuaError(Throwable cause) { @@ -94,7 +95,7 @@ public class LuaError extends RuntimeException { /** * Construct a LuaError with a specific message. - * + * * @param message message to supply */ public LuaError(String message) { @@ -105,7 +106,7 @@ public class LuaError extends RuntimeException { /** * Construct a LuaError with a message, and level to draw line number * information from. - * + * * @param message message to supply * @param level where to supply line info from in call stack */ @@ -117,7 +118,7 @@ public class LuaError extends RuntimeException { /** * Construct a LuaError with a LuaValue as the message object, and level to * draw line number information from. - * + * * @param message_object message string or object to supply */ public LuaError(LuaValue message_object) { @@ -129,6 +130,7 @@ public class LuaError extends RuntimeException { /** * Get the cause, if any. */ + @Override public Throwable getCause() { return cause; } } diff --git a/luaj-core/src/main/java/org/luaj/vm2/LuaFunction.java b/luaj-core/src/main/java/org/luaj/vm2/LuaFunction.java index e1f8e647..38403bd7 100644 --- a/luaj-core/src/main/java/org/luaj/vm2/LuaFunction.java +++ b/luaj-core/src/main/java/org/luaj/vm2/LuaFunction.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 @@ -28,7 +28,7 @@ package org.luaj.vm2; * base class for all built-in library functions coded in Java, and * {@link LuaClosure}, which represents a lua closure whose bytecode is * interpreted when the function is invoked. - * + * * @see LuaValue * @see LuaClosure * @see org.luaj.vm2.lib.LibFunction @@ -38,34 +38,42 @@ abstract public class LuaFunction extends LuaValue { /** Shared static metatable for all functions and closures. */ public static LuaValue s_metatable; + @Override public int type() { return TFUNCTION; } + @Override public String typename() { return "function"; } + @Override public boolean isfunction() { return true; } + @Override public LuaFunction checkfunction() { return this; } + @Override public LuaFunction optfunction(LuaFunction defval) { return this; } + @Override public LuaValue getmetatable() { return s_metatable; } + @Override public String tojstring() { return "function: " + classnamestub(); } + @Override public LuaString strvalue() { return valueOf(tojstring()); } @@ -73,7 +81,7 @@ abstract public class LuaFunction extends LuaValue { /** * Return the last part of the class name, to be used as a function name in * tojstring and elsewhere. - * + * * @return String naming the last part of the class name after the last dot * (.) or dollar sign ($). If the first character is '_', it is * skipped. @@ -90,7 +98,7 @@ abstract public class LuaFunction extends LuaValue { * Return a human-readable name for this function. Returns the last part of * the class name by default. Is overridden by LuaClosure to return the * source file and line, and by LibFunctions to return the name. - * + * * @return common name for this function. */ public String name() { diff --git a/luaj-core/src/main/java/org/luaj/vm2/LuaInteger.java b/luaj-core/src/main/java/org/luaj/vm2/LuaInteger.java index 867cec74..ac41cb9b 100644 --- a/luaj-core/src/main/java/org/luaj/vm2/LuaInteger.java +++ b/luaj-core/src/main/java/org/luaj/vm2/LuaInteger.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 @@ -33,7 +33,7 @@ import org.luaj.vm2.lib.MathLib; *

    * There are no API's specific to LuaInteger that are useful beyond what is * already exposed in {@link LuaValue}. - * + * * @see LuaValue * @see LuaNumber * @see LuaDouble @@ -50,12 +50,12 @@ public class LuaInteger extends LuaNumber { public static LuaInteger valueOf(int i) { return i <= 255 && i >= -256? intValues[i+256]: new LuaInteger(i); - }; + } // TODO consider moving this to LuaValue /** * Return a LuaNumber that represents the value provided - * + * * @param l long value to represent. * @return LuaNumber that is eithe LuaInteger or LuaDouble representing l * @see LuaValue#valueOf(int) @@ -63,7 +63,7 @@ public class LuaInteger extends LuaNumber { */ public static LuaNumber valueOf(long l) { int i = (int) l; - return l == i? (i <= 255 && i >= -256? intValues[i+256]: (LuaNumber) new LuaInteger(i)) + return l == i? i <= 255 && i >= -256? intValues[i+256]: (LuaNumber) new LuaInteger(i) : (LuaNumber) LuaDouble.valueOf(l); } @@ -72,69 +72,91 @@ public class LuaInteger extends LuaNumber { /** * Package protected constructor. - * + * * @see LuaValue#valueOf(int) **/ LuaInteger(int i) { this.v = i; } + @Override public boolean isint() { return true; } + @Override public boolean isinttype() { return true; } + @Override public boolean islong() { return true; } + @Override public byte tobyte() { return (byte) v; } + @Override public char tochar() { return (char) v; } + @Override public double todouble() { return v; } + @Override public float tofloat() { return v; } + @Override public int toint() { return v; } + @Override public long tolong() { return v; } + @Override public short toshort() { return (short) v; } + @Override public double optdouble(double defval) { return v; } + @Override public int optint(int defval) { return v; } + @Override public LuaInteger optinteger(LuaInteger defval) { return this; } + @Override public long optlong(long defval) { return v; } + @Override public String tojstring() { return Integer.toString(v); } + @Override public LuaString strvalue() { return LuaString.valueOf(Integer.toString(v)); } + @Override public LuaString optstring(LuaString defval) { return LuaString.valueOf(Integer.toString(v)); } + @Override public LuaValue tostring() { return LuaString.valueOf(Integer.toString(v)); } + @Override public String optjstring(String defval) { return Integer.toString(v); } + @Override public LuaInteger checkinteger() { return this; } + @Override public boolean isstring() { return true; } + @Override public int hashCode() { return v; } @@ -144,144 +166,205 @@ public class LuaInteger extends LuaNumber { } // unary operators + @Override public LuaValue neg() { return valueOf(-(long) v); } // object equality, used for key comparison + @Override public boolean equals(Object o) { return o instanceof LuaInteger? ((LuaInteger) o).v == v: false; } // equality w/ metatable processing + @Override public LuaValue eq(LuaValue val) { return val.raweq(v)? TRUE: FALSE; } + @Override public boolean eq_b(LuaValue val) { return val.raweq(v); } // equality w/o metatable processing + @Override public boolean raweq(LuaValue val) { return val.raweq(v); } + @Override public boolean raweq(double val) { return v == val; } + @Override public boolean raweq(int val) { return v == val; } // arithmetic operators + @Override public LuaValue add(LuaValue rhs) { return rhs.add(v); } + @Override public LuaValue add(double lhs) { return LuaDouble.valueOf(lhs+v); } + @Override public LuaValue add(int lhs) { return LuaInteger.valueOf(lhs+(long) v); } + @Override public LuaValue sub(LuaValue rhs) { return rhs.subFrom(v); } + @Override public LuaValue sub(double rhs) { return LuaDouble.valueOf(v-rhs); } - public LuaValue sub(int rhs) { return LuaDouble.valueOf(v-rhs); } + @Override + public LuaValue sub(int rhs) { return LuaValue.valueOf(v-rhs); } + @Override public LuaValue subFrom(double lhs) { return LuaDouble.valueOf(lhs-v); } + @Override public LuaValue subFrom(int lhs) { return LuaInteger.valueOf(lhs-(long) v); } + @Override public LuaValue mul(LuaValue rhs) { return rhs.mul(v); } + @Override public LuaValue mul(double lhs) { return LuaDouble.valueOf(lhs*v); } + @Override public LuaValue mul(int lhs) { return LuaInteger.valueOf(lhs*(long) v); } + @Override public LuaValue pow(LuaValue rhs) { return rhs.powWith(v); } + @Override public LuaValue pow(double rhs) { return MathLib.dpow(v, rhs); } + @Override public LuaValue pow(int rhs) { return MathLib.dpow(v, rhs); } + @Override public LuaValue powWith(double lhs) { return MathLib.dpow(lhs, v); } + @Override public LuaValue powWith(int lhs) { return MathLib.dpow(lhs, v); } + @Override public LuaValue div(LuaValue rhs) { return rhs.divInto(v); } + @Override public LuaValue div(double rhs) { return LuaDouble.ddiv(v, rhs); } + @Override public LuaValue div(int rhs) { return LuaDouble.ddiv(v, rhs); } + @Override public LuaValue divInto(double lhs) { return LuaDouble.ddiv(lhs, v); } + @Override public LuaValue mod(LuaValue rhs) { return rhs.modFrom(v); } + @Override public LuaValue mod(double rhs) { return LuaDouble.dmod(v, rhs); } + @Override public LuaValue mod(int rhs) { return LuaDouble.dmod(v, rhs); } + @Override public LuaValue modFrom(double lhs) { return LuaDouble.dmod(lhs, v); } // relational operators - public LuaValue lt(LuaValue rhs) { return rhs instanceof LuaNumber? (rhs.gt_b(v)? TRUE: FALSE): super.lt(rhs); } + @Override + public LuaValue lt(LuaValue rhs) { return rhs instanceof LuaNumber? rhs.gt_b(v)? TRUE: FALSE: super.lt(rhs); } + @Override public LuaValue lt(double rhs) { return v < rhs? TRUE: FALSE; } + @Override public LuaValue lt(int rhs) { return v < rhs? TRUE: FALSE; } + @Override public boolean lt_b(LuaValue rhs) { return rhs instanceof LuaNumber? rhs.gt_b(v): super.lt_b(rhs); } + @Override public boolean lt_b(int rhs) { return v < rhs; } + @Override public boolean lt_b(double rhs) { return v < rhs; } + @Override public LuaValue lteq(LuaValue rhs) { - return rhs instanceof LuaNumber? (rhs.gteq_b(v)? TRUE: FALSE): super.lteq(rhs); + return rhs instanceof LuaNumber? rhs.gteq_b(v)? TRUE: FALSE: super.lteq(rhs); } + @Override public LuaValue lteq(double rhs) { return v <= rhs? TRUE: FALSE; } + @Override public LuaValue lteq(int rhs) { return v <= rhs? TRUE: FALSE; } + @Override public boolean lteq_b(LuaValue rhs) { return rhs instanceof LuaNumber? rhs.gteq_b(v): super.lteq_b(rhs); } + @Override public boolean lteq_b(int rhs) { return v <= rhs; } + @Override public boolean lteq_b(double rhs) { return v <= rhs; } - public LuaValue gt(LuaValue rhs) { return rhs instanceof LuaNumber? (rhs.lt_b(v)? TRUE: FALSE): super.gt(rhs); } + @Override + public LuaValue gt(LuaValue rhs) { return rhs instanceof LuaNumber? rhs.lt_b(v)? TRUE: FALSE: super.gt(rhs); } + @Override public LuaValue gt(double rhs) { return v > rhs? TRUE: FALSE; } + @Override public LuaValue gt(int rhs) { return v > rhs? TRUE: FALSE; } + @Override public boolean gt_b(LuaValue rhs) { return rhs instanceof LuaNumber? rhs.lt_b(v): super.gt_b(rhs); } + @Override public boolean gt_b(int rhs) { return v > rhs; } + @Override public boolean gt_b(double rhs) { return v > rhs; } + @Override public LuaValue gteq(LuaValue rhs) { - return rhs instanceof LuaNumber? (rhs.lteq_b(v)? TRUE: FALSE): super.gteq(rhs); + return rhs instanceof LuaNumber? rhs.lteq_b(v)? TRUE: FALSE: super.gteq(rhs); } + @Override public LuaValue gteq(double rhs) { return v >= rhs? TRUE: FALSE; } + @Override public LuaValue gteq(int rhs) { return v >= rhs? TRUE: FALSE; } + @Override public boolean gteq_b(LuaValue rhs) { return rhs instanceof LuaNumber? rhs.lteq_b(v): super.gteq_b(rhs); } + @Override public boolean gteq_b(int rhs) { return v >= rhs; } + @Override public boolean gteq_b(double rhs) { return v >= rhs; } // string comparison + @Override public int strcmp(LuaString rhs) { typerror("attempt to compare number with string"); return 0; } + @Override public int checkint() { return v; } + @Override public long checklong() { return v; } + @Override public double checkdouble() { return v; } + @Override public String checkjstring() { return String.valueOf(v); } + @Override public LuaString checkstring() { return valueOf(String.valueOf(v)); } diff --git a/luaj-core/src/main/java/org/luaj/vm2/LuaNil.java b/luaj-core/src/main/java/org/luaj/vm2/LuaNil.java index b0ab3822..ace94717 100644 --- a/luaj-core/src/main/java/org/luaj/vm2/LuaNil.java +++ b/luaj-core/src/main/java/org/luaj/vm2/LuaNil.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 @@ -33,7 +33,7 @@ package org.luaj.vm2; * recommended approach is to use the method {@link LuaValue#isnil()} instead. * By using that any ambiguities between {@link LuaValue#NIL} and * {@link LuaValue#NONE} are avoided. - * + * * @see LuaValue * @see LuaValue#NIL */ @@ -45,78 +45,104 @@ public class LuaNil extends LuaValue { LuaNil() {} + @Override public int type() { return LuaValue.TNIL; } + @Override public String toString() { return "nil"; } + @Override public String typename() { return "nil"; } + @Override public String tojstring() { return "nil"; } + @Override public LuaValue not() { return LuaValue.TRUE; } + @Override public boolean toboolean() { return false; } + @Override public boolean isnil() { return true; } + @Override public LuaValue getmetatable() { return s_metatable; } + @Override public boolean equals(Object o) { return o instanceof LuaNil; } + @Override public LuaValue checknotnil() { return argerror("value"); } + @Override public boolean isvalidkey() { return false; } // optional argument conversions - nil alwas falls badk to default value + @Override public boolean optboolean(boolean defval) { return defval; } + @Override public LuaClosure optclosure(LuaClosure defval) { return defval; } + @Override public double optdouble(double defval) { return defval; } + @Override public LuaFunction optfunction(LuaFunction defval) { return defval; } + @Override public int optint(int defval) { return defval; } + @Override public LuaInteger optinteger(LuaInteger defval) { return defval; } + @Override public long optlong(long defval) { return defval; } + @Override public LuaNumber optnumber(LuaNumber defval) { return defval; } + @Override public LuaTable opttable(LuaTable defval) { return defval; } + @Override public LuaThread optthread(LuaThread defval) { return defval; } + @Override public String optjstring(String defval) { return defval; } + @Override public LuaString optstring(LuaString defval) { return defval; } + @Override public Object optuserdata(Object defval) { return defval; } + @Override public Object optuserdata(Class c, Object defval) { return defval; } + @Override public LuaValue optvalue(LuaValue defval) { return defval; } } diff --git a/luaj-core/src/main/java/org/luaj/vm2/LuaNumber.java b/luaj-core/src/main/java/org/luaj/vm2/LuaNumber.java index 57fa8d27..b1dd89f2 100644 --- a/luaj-core/src/main/java/org/luaj/vm2/LuaNumber.java +++ b/luaj-core/src/main/java/org/luaj/vm2/LuaNumber.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,59 +26,72 @@ package org.luaj.vm2; *

    * The main subclasses are {@link LuaInteger} which holds values that fit in a * java int, and {@link LuaDouble} which holds all other number values. - * + * * @see LuaInteger * @see LuaDouble * @see LuaValue - * + * */ abstract public class LuaNumber extends LuaValue { /** Shared static metatable for all number values represented in lua. */ public static LuaValue s_metatable; + @Override public int type() { return TNUMBER; } + @Override public String typename() { return "number"; } + @Override public LuaNumber checknumber() { return this; } + @Override public LuaNumber checknumber(String errmsg) { return this; } + @Override public LuaNumber optnumber(LuaNumber defval) { return this; } + @Override public LuaValue tonumber() { return this; } + @Override public boolean isnumber() { return true; } + @Override public boolean isstring() { return true; } + @Override public LuaValue getmetatable() { return s_metatable; } + @Override public LuaValue concat(LuaValue rhs) { return rhs.concatTo(this); } + @Override public Buffer concat(Buffer rhs) { return rhs.concatTo(this); } + @Override public LuaValue concatTo(LuaNumber lhs) { return strvalue().concatTo(lhs.strvalue()); } + @Override public LuaValue concatTo(LuaString lhs) { return strvalue().concatTo(lhs); } } diff --git a/luaj-core/src/main/java/org/luaj/vm2/LuaString.java b/luaj-core/src/main/java/org/luaj/vm2/LuaString.java index b0a56eb1..1746240d 100644 --- a/luaj-core/src/main/java/org/luaj/vm2/LuaString.java +++ b/luaj-core/src/main/java/org/luaj/vm2/LuaString.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 @@ -53,7 +53,7 @@ import org.luaj.vm2.lib.MathLib; * {@link #encodeToUtf8(char[], int, byte[], int)}, and * {@link #decodeAsUtf8(byte[], int, int)} are used to convert back and forth * between UTF8 byte arrays and character arrays. - * + * * @see LuaValue * @see LuaValue#valueOf(String) * @see LuaValue#valueOf(byte[]) @@ -116,7 +116,7 @@ public class LuaString extends LuaValue { /** * Get a {@link LuaString} instance whose bytes match the supplied Java * String using the UTF8 encoding. - * + * * @param string Java String containing characters to encode as UTF8 * @return {@link LuaString} with UTF8 bytes corresponding to the supplied * String @@ -137,7 +137,7 @@ public class LuaString extends LuaValue { * the backing, otherwise the bytes will be copied to a new byte array, and * cache lookup may be performed. *

    - * + * * @param bytes byte buffer * @param off offset into the byte buffer * @param len length of the byte buffer @@ -147,7 +147,7 @@ public class LuaString extends LuaValue { if (len > RECENT_STRINGS_MAX_LENGTH) return valueFromCopy(bytes, off, len); final int hash = hashCode(bytes, off, len); - final int bucket = hash & (RECENT_STRINGS_CACHE_SIZE-1); + final int bucket = hash & RECENT_STRINGS_CACHE_SIZE-1; final LuaString t = RecentShortStrings.recent_short_strings[bucket]; if (t != null && t.m_hashcode == hash && t.byteseq(bytes, off, len)) return t; @@ -171,7 +171,7 @@ public class LuaString extends LuaValue { * However, if the string is short enough the short-string cache is checked * for a match which may be used instead of the supplied byte array. *

    - * + * * @param bytes byte buffer * @return {@link LuaString} wrapping the byte buffer, or an equivalent * string. @@ -180,7 +180,7 @@ public class LuaString extends LuaValue { if (bytes.length > RECENT_STRINGS_MAX_LENGTH) return new LuaString(bytes, off, len); final int hash = hashCode(bytes, off, len); - final int bucket = hash & (RECENT_STRINGS_CACHE_SIZE-1); + final int bucket = hash & RECENT_STRINGS_CACHE_SIZE-1; final LuaString t = RecentShortStrings.recent_short_strings[bucket]; if (t != null && t.m_hashcode == hash && t.byteseq(bytes, off, len)) return t; @@ -198,7 +198,7 @@ public class LuaString extends LuaValue { *

    * This is most useful for constructing byte sequences that do not conform * to UTF8. - * + * * @param bytes array of char, whose values are truncated at 8-bits each and * put into a byte array. * @return {@link LuaString} wrapping a copy of the byte buffer @@ -216,7 +216,7 @@ public class LuaString extends LuaValue { *

    * This is most useful for constructing byte sequences that do not conform * to UTF8. - * + * * @param bytes array of char, whose values are truncated at 8-bits each and * put into a byte array. * @return {@link LuaString} wrapping a copy of the byte buffer @@ -235,7 +235,7 @@ public class LuaString extends LuaValue { * of the bytes array, or be an existing LuaString used already having the * same value. *

    - * + * * @param bytes byte buffer * @return {@link LuaString} wrapping the byte buffer */ @@ -252,7 +252,7 @@ public class LuaString extends LuaValue { *

    * The caller must not mutate the contents of the byte array after this * call, as it may be used elsewhere due to recent short string caching. - * + * * @param bytes byte buffer * @return {@link LuaString} wrapping the byte buffer */ @@ -267,7 +267,7 @@ public class LuaString extends LuaValue { * The array is used directly after this is called, so clients must not * change contents. *

    - * + * * @param bytes byte buffer * @param offset offset into the byte buffer * @param length length of the byte buffer @@ -280,142 +280,191 @@ public class LuaString extends LuaValue { this.m_hashcode = hashCode(bytes, offset, length); } + @Override public boolean isstring() { return true; } + @Override public LuaValue getmetatable() { return s_metatable; } + @Override public int type() { return LuaValue.TSTRING; } + @Override public String typename() { return "string"; } + @Override public String tojstring() { return decodeAsUtf8(m_bytes, m_offset, m_length); } // unary operators + @Override public LuaValue neg() { double d = scannumber(); return Double.isNaN(d)? super.neg(): valueOf(-d); } // basic binary arithmetic + @Override public LuaValue add(LuaValue rhs) { double d = scannumber(); return Double.isNaN(d)? arithmt(ADD, rhs): rhs.add(d); } + @Override public LuaValue add(double rhs) { return valueOf(checkarith()+rhs); } + @Override public LuaValue add(int rhs) { return valueOf(checkarith()+rhs); } + @Override public LuaValue sub(LuaValue rhs) { double d = scannumber(); return Double.isNaN(d)? arithmt(SUB, rhs): rhs.subFrom(d); } + @Override public LuaValue sub(double rhs) { return valueOf(checkarith()-rhs); } + @Override public LuaValue sub(int rhs) { return valueOf(checkarith()-rhs); } + @Override public LuaValue subFrom(double lhs) { return valueOf(lhs-checkarith()); } + @Override public LuaValue mul(LuaValue rhs) { double d = scannumber(); return Double.isNaN(d)? arithmt(MUL, rhs): rhs.mul(d); } + @Override public LuaValue mul(double rhs) { return valueOf(checkarith()*rhs); } + @Override public LuaValue mul(int rhs) { return valueOf(checkarith()*rhs); } + @Override public LuaValue pow(LuaValue rhs) { double d = scannumber(); return Double.isNaN(d)? arithmt(POW, rhs): rhs.powWith(d); } + @Override public LuaValue pow(double rhs) { return MathLib.dpow(checkarith(), rhs); } + @Override public LuaValue pow(int rhs) { return MathLib.dpow(checkarith(), rhs); } + @Override public LuaValue powWith(double lhs) { return MathLib.dpow(lhs, checkarith()); } + @Override public LuaValue powWith(int lhs) { return MathLib.dpow(lhs, checkarith()); } + @Override public LuaValue div(LuaValue rhs) { double d = scannumber(); return Double.isNaN(d)? arithmt(DIV, rhs): rhs.divInto(d); } + @Override public LuaValue div(double rhs) { return LuaDouble.ddiv(checkarith(), rhs); } + @Override public LuaValue div(int rhs) { return LuaDouble.ddiv(checkarith(), rhs); } + @Override public LuaValue divInto(double lhs) { return LuaDouble.ddiv(lhs, checkarith()); } + @Override public LuaValue mod(LuaValue rhs) { double d = scannumber(); return Double.isNaN(d)? arithmt(MOD, rhs): rhs.modFrom(d); } + @Override public LuaValue mod(double rhs) { return LuaDouble.dmod(checkarith(), rhs); } + @Override public LuaValue mod(int rhs) { return LuaDouble.dmod(checkarith(), rhs); } + @Override public LuaValue modFrom(double lhs) { return LuaDouble.dmod(lhs, checkarith()); } // relational operators, these only work with other strings + @Override public LuaValue lt(LuaValue rhs) { - return rhs.isstring()? (rhs.strcmp(this) > 0? LuaValue.TRUE: FALSE): super.lt(rhs); + return rhs.isstring()? rhs.strcmp(this) > 0? LuaValue.TRUE: FALSE: super.lt(rhs); } + @Override public boolean lt_b(LuaValue rhs) { return rhs.isstring()? rhs.strcmp(this) > 0: super.lt_b(rhs); } + @Override public boolean lt_b(int rhs) { typerror("attempt to compare string with number"); return false; } + @Override public boolean lt_b(double rhs) { typerror("attempt to compare string with number"); return false; } + @Override public LuaValue lteq(LuaValue rhs) { - return rhs.isstring()? (rhs.strcmp(this) >= 0? LuaValue.TRUE: FALSE): super.lteq(rhs); + return rhs.isstring()? rhs.strcmp(this) >= 0? LuaValue.TRUE: FALSE: super.lteq(rhs); } + @Override public boolean lteq_b(LuaValue rhs) { return rhs.isstring()? rhs.strcmp(this) >= 0: super.lteq_b(rhs); } + @Override public boolean lteq_b(int rhs) { typerror("attempt to compare string with number"); return false; } + @Override public boolean lteq_b(double rhs) { typerror("attempt to compare string with number"); return false; } + @Override public LuaValue gt(LuaValue rhs) { - return rhs.isstring()? (rhs.strcmp(this) < 0? LuaValue.TRUE: FALSE): super.gt(rhs); + return rhs.isstring()? rhs.strcmp(this) < 0? LuaValue.TRUE: FALSE: super.gt(rhs); } + @Override public boolean gt_b(LuaValue rhs) { return rhs.isstring()? rhs.strcmp(this) < 0: super.gt_b(rhs); } + @Override public boolean gt_b(int rhs) { typerror("attempt to compare string with number"); return false; } + @Override public boolean gt_b(double rhs) { typerror("attempt to compare string with number"); return false; } + @Override public LuaValue gteq(LuaValue rhs) { - return rhs.isstring()? (rhs.strcmp(this) <= 0? LuaValue.TRUE: FALSE): super.gteq(rhs); + return rhs.isstring()? rhs.strcmp(this) <= 0? LuaValue.TRUE: FALSE: super.gteq(rhs); } + @Override public boolean gteq_b(LuaValue rhs) { return rhs.isstring()? rhs.strcmp(this) <= 0: super.gteq_b(rhs); } + @Override public boolean gteq_b(int rhs) { typerror("attempt to compare string with number"); return false; } + @Override public boolean gteq_b(double rhs) { typerror("attempt to compare string with number"); return false; } // concatenation + @Override public LuaValue concat(LuaValue rhs) { return rhs.concatTo(this); } + @Override public Buffer concat(Buffer rhs) { return rhs.concatTo(this); } + @Override public LuaValue concatTo(LuaNumber lhs) { return concatTo(lhs.strvalue()); } + @Override public LuaValue concatTo(LuaString lhs) { byte[] b = new byte[lhs.m_length+this.m_length]; System.arraycopy(lhs.m_bytes, lhs.m_offset, b, 0, lhs.m_length); @@ -424,12 +473,14 @@ public class LuaString extends LuaValue { } // string comparison + @Override public int strcmp(LuaValue lhs) { return -lhs.strcmp(this); } + @Override public int strcmp(LuaString rhs) { for (int i = 0, j = 0; i < m_length && j < rhs.m_length; ++i, ++j) { if (m_bytes[m_offset+i] != rhs.m_bytes[rhs.m_offset+j]) { - return ((int) m_bytes[m_offset+i])-((int) rhs.m_bytes[rhs.m_offset+j]); + return m_bytes[m_offset+i]-rhs.m_bytes[rhs.m_offset+j]; } } return m_length-rhs.m_length; @@ -443,18 +494,22 @@ public class LuaString extends LuaValue { return d; } + @Override public int checkint() { return (int) (long) checkdouble(); } + @Override public LuaInteger checkinteger() { return valueOf(checkint()); } + @Override public long checklong() { return (long) checkdouble(); } + @Override public double checkdouble() { double d = scannumber(); if (Double.isNaN(d)) @@ -462,10 +517,12 @@ public class LuaString extends LuaValue { return d; } + @Override public LuaNumber checknumber() { return valueOf(checkdouble()); } + @Override public LuaNumber checknumber(String msg) { double d = scannumber(); if (Double.isNaN(d)) @@ -473,11 +530,13 @@ public class LuaString extends LuaValue { return valueOf(d); } + @Override public boolean isnumber() { double d = scannumber(); return !Double.isNaN(d); } + @Override public boolean isint() { double d = scannumber(); if (Double.isNaN(d)) @@ -486,6 +545,7 @@ public class LuaString extends LuaValue { return i == d; } + @Override public boolean islong() { double d = scannumber(); if (Double.isNaN(d)) @@ -494,52 +554,68 @@ public class LuaString extends LuaValue { return l == d; } + @Override public byte tobyte() { return (byte) toint(); } + @Override public char tochar() { return (char) toint(); } + @Override public double todouble() { double d = scannumber(); return Double.isNaN(d)? 0: d; } + @Override public float tofloat() { return (float) todouble(); } + @Override public int toint() { return (int) tolong(); } + @Override public long tolong() { return (long) todouble(); } + @Override public short toshort() { return (short) toint(); } + @Override public double optdouble(double defval) { return checkdouble(); } + @Override public int optint(int defval) { return checkint(); } + @Override public LuaInteger optinteger(LuaInteger defval) { return checkinteger(); } + @Override public long optlong(long defval) { return checklong(); } + @Override public LuaNumber optnumber(LuaNumber defval) { return checknumber(); } + @Override public LuaString optstring(LuaString defval) { return this; } + @Override public LuaValue tostring() { return this; } + @Override public String optjstring(String defval) { return tojstring(); } + @Override public LuaString strvalue() { return this; } @@ -547,7 +623,7 @@ public class LuaString extends LuaValue { /** * Take a substring using Java zero-based indexes for begin and end or * range. - * + * * @param beginIndex The zero-based index of the first character to include. * @param endIndex The zero-based index of position after the last * character. @@ -560,6 +636,7 @@ public class LuaString extends LuaValue { return len >= m_length/2? valueUsing(m_bytes, off, len): valueOf(m_bytes, off, len); } + @Override public int hashCode() { return m_hashcode; } @@ -568,7 +645,7 @@ public class LuaString extends LuaValue { * Compute the hash code of a sequence of bytes within a byte array using * lua's rules for string hashes. For long strings, not all bytes are * hashed. - * + * * @param bytes byte array containing the bytes. * @param offset offset into the hash for the first byte. * @param length number of bytes starting with offset that are part of the @@ -579,11 +656,12 @@ public class LuaString extends LuaValue { int h = length; /* seed */ int step = (length>>5)+1; /* if string is too long, don't hash all its chars */ for (int l1 = length; l1 >= step; l1 -= step) /* compute hash */ - h = h ^ ((h<<5)+(h>>2)+(((int) bytes[offset+l1-1]) & 0x0FF)); + h = h ^ (h<<5)+(h>>2)+(bytes[offset+l1-1] & 0x0FF); return h; } // object comparison, used in key comparison + @Override public boolean equals(Object o) { if (o instanceof LuaString) { return raweq((LuaString) o); @@ -592,15 +670,19 @@ public class LuaString extends LuaValue { } // equality w/ metatable processing + @Override public LuaValue eq(LuaValue val) { return val.raweq(this)? TRUE: FALSE; } + @Override public boolean eq_b(LuaValue val) { return val.raweq(this); } // equality w/o metatable processing + @Override public boolean raweq(LuaValue val) { return val.raweq(this); } + @Override public boolean raweq(LuaString s) { if (this == s) return true; @@ -625,7 +707,7 @@ public class LuaString extends LuaValue { * bytes. */ private boolean byteseq(byte[] bytes, int off, int len) { - return (m_length == len && equals(m_bytes, m_offset, bytes, off, len)); + return m_length == len && equals(m_bytes, m_offset, bytes, off, len); } public static boolean equals(byte[] a, int i, byte[] b, int j, int n) { @@ -641,14 +723,17 @@ public class LuaString extends LuaValue { writer.write(m_bytes, m_offset+i, len); } + @Override public LuaValue len() { return LuaInteger.valueOf(m_length); } + @Override public int length() { return m_length; } + @Override public int rawlen() { return m_length; } @@ -663,17 +748,19 @@ public class LuaString extends LuaValue { return luaByte(index); } + @Override public String checkjstring() { return tojstring(); } + @Override public LuaString checkstring() { return this; } /** * Convert value to an input stream. - * + * * @return {@link InputStream} whose data matches the bytes in this * {@link LuaString} */ @@ -683,7 +770,7 @@ public class LuaString extends LuaValue { /** * Copy the bytes of the string into the given byte array. - * + * * @param strOffset offset from which to copy * @param bytes destination byte array * @param arrayOffset offset in destination @@ -696,7 +783,7 @@ public class LuaString extends LuaValue { /** * Java version of strpbrk - find index of any byte that in an accept * string. - * + * * @param accept {@link LuaString} containing characters to look for. * @return index of first match in the {@code accept} string, or -1 if not * found. @@ -716,7 +803,7 @@ public class LuaString extends LuaValue { /** * Find the index of a byte starting at a point in this string - * + * * @param b the byte to look for * @param start the first index in the string * @return index of first match found, or -1 if not found. @@ -731,7 +818,7 @@ public class LuaString extends LuaValue { /** * Find the index of a string starting at a point in this string - * + * * @param s the string to search for * @param start the first index in the string * @return index of first match found, or -1 if not found. @@ -748,7 +835,7 @@ public class LuaString extends LuaValue { /** * Find the last index of a string in this string - * + * * @param s the string to search for * @return index of last match found, or -1 if not found. */ @@ -764,7 +851,7 @@ public class LuaString extends LuaValue { /** * Convert to Java String interpreting as utf8 characters. - * + * * @param bytes byte array in UTF8 encoding to convert * @param offset starting index in byte array * @param length number of bytes to convert @@ -786,16 +873,16 @@ public class LuaString extends LuaValue { } char[] chars = new char[n]; for (i = offset, j = offset+length, n = 0; i < j;) { - chars[n++] = (char) (((b = bytes[i++]) >= 0 || i >= j)? b - : (b < -32 || i+1 >= j)? (((b & 0x3f)<<6) | (bytes[i++] & 0x3f)) - : (((b & 0xf)<<12) | ((bytes[i++] & 0x3f)<<6) | (bytes[i++] & 0x3f))); + chars[n++] = (char) ((b = bytes[i++]) >= 0 || i >= j? b + : b < -32 || i+1 >= j? (b & 0x3f)<<6 | bytes[i++] & 0x3f + : (b & 0xf)<<12 | (bytes[i++] & 0x3f)<<6 | bytes[i++] & 0x3f); } return new String(chars); } /** * Count the number of bytes required to encode the string as UTF-8. - * + * * @param chars Array of unicode characters to be encoded as UTF-8 * @return count of bytes needed to encode using UTF-8 * @see #encodeToUtf8(char[], int, byte[], int) @@ -807,7 +894,7 @@ public class LuaString extends LuaValue { char c; for (i = b = chars.length; --i >= 0;) if ((c = chars[i]) >= 0x80) - b += (c >= 0x800)? 2: 1; + b += c >= 0x800? 2: 1; return b; } @@ -817,7 +904,7 @@ public class LuaString extends LuaValue { *

    * The string should be measured first with lengthAsUtf8 to make sure the * given byte array is large enough. - * + * * @param chars Array of unicode characters to be encoded as UTF-8 * @param nchars Number of characters in the array to convert. * @param bytes byte array to hold the result @@ -834,12 +921,12 @@ public class LuaString extends LuaValue { if ((c = chars[i]) < 0x80) { bytes[j++] = (byte) c; } else if (c < 0x800) { - bytes[j++] = (byte) (0xC0 | ((c>>6) & 0x1f)); - bytes[j++] = (byte) (0x80 | (c & 0x3f)); + bytes[j++] = (byte) (0xC0 | c>>6 & 0x1f); + bytes[j++] = (byte) (0x80 | c & 0x3f); } else { - bytes[j++] = (byte) (0xE0 | ((c>>12) & 0x0f)); - bytes[j++] = (byte) (0x80 | ((c>>6) & 0x3f)); - bytes[j++] = (byte) (0x80 | (c & 0x3f)); + bytes[j++] = (byte) (0xE0 | c>>12 & 0x0f); + bytes[j++] = (byte) (0x80 | c>>6 & 0x3f); + bytes[j++] = (byte) (0x80 | c & 0x3f); } } return j-off; @@ -847,7 +934,7 @@ public class LuaString extends LuaValue { /** * Check that a byte sequence is valid UTF-8 - * + * * @return true if it is valid UTF-8, otherwise false * @see #lengthAsUtf8(char[]) * @see #encodeToUtf8(char[], int, byte[], int) @@ -856,11 +943,9 @@ public class LuaString extends LuaValue { public boolean isValidUtf8() { for (int i = m_offset, j = m_offset+m_length; i < j;) { int c = m_bytes[i++]; - if (c >= 0) + if (c >= 0 || (c & 0xE0) == 0xC0 && i < j && (m_bytes[i++] & 0xC0) == 0x80) continue; - if (((c & 0xE0) == 0xC0) && i < j && (m_bytes[i++] & 0xC0) == 0x80) - continue; - if (((c & 0xF0) == 0xE0) && i+1 < j && (m_bytes[i++] & 0xC0) == 0x80 && (m_bytes[i++] & 0xC0) == 0x80) + if ((c & 0xF0) == 0xE0 && i+1 < j && (m_bytes[i++] & 0xC0) == 0x80 && (m_bytes[i++] & 0xC0) == 0x80) continue; return false; } @@ -872,11 +957,12 @@ public class LuaString extends LuaValue { /** * convert to a number using baee 10 or base 16 if it starts with '0x', or * NIL if it can't be converted - * + * * @return IntValue, DoubleValue, or NIL depending on the content of the * string. * @see LuaValue#tonumber() */ + @Override public LuaValue tonumber() { double d = scannumber(); return Double.isNaN(d)? NIL: valueOf(d); @@ -885,7 +971,7 @@ public class LuaString extends LuaValue { /** * convert to a number using a supplied base, or NIL if it can't be * converted - * + * * @param base the base to use, such as 10 * @return IntValue, DoubleValue, or NIL depending on the content of the * string. @@ -899,7 +985,7 @@ public class LuaString extends LuaValue { /** * Convert to a number in base 10, or base 16 if the string starts with * '0x', or return Double.NaN if it cannot be converted to a number. - * + * * @return double value if conversion is valid, or Double.NaN if not */ public double scannumber() { @@ -918,7 +1004,7 @@ public class LuaString extends LuaValue { /** * Convert to a number in a base, or return Double.NaN if not a number. - * + * * @param base the base to use between 2 and 36 * @return double value if conversion is valid, or Double.NaN if not */ @@ -937,7 +1023,7 @@ public class LuaString extends LuaValue { /** * Scan and convert a long value, or return Double.NaN if not found. - * + * * @param base the base to use, such as 10 * @param start the index to start searching from * @param end the first index beyond the search range @@ -945,10 +1031,10 @@ public class LuaString extends LuaValue { */ private double scanlong(int base, int start, int end) { long x = 0; - boolean neg = (m_bytes[start] == '-'); - for (int i = (neg? start+1: start); i < end; i++) { - int digit = m_bytes[i]-(base <= 10 || (m_bytes[i] >= '0' && m_bytes[i] <= '9')? '0' - : m_bytes[i] >= 'A' && m_bytes[i] <= 'Z'? ('A'-10): ('a'-10)); + boolean neg = m_bytes[start] == '-'; + for (int i = neg? start+1: start; i < end; i++) { + int digit = m_bytes[i]-(base <= 10 || m_bytes[i] >= '0' && m_bytes[i] <= '9'? '0' + : m_bytes[i] >= 'A' && m_bytes[i] <= 'Z'? 'A'-10: 'a'-10); if (digit < 0 || digit >= base) return Double.NaN; x = x*base+digit; @@ -960,7 +1046,7 @@ public class LuaString extends LuaValue { /** * Scan and convert a double value, or return Double.NaN if not a double. - * + * * @param start the index to start searching from * @param end the first index beyond the search range * @return double value if conversion is valid, or Double.NaN if not @@ -1003,7 +1089,7 @@ public class LuaString extends LuaValue { /** * Print the bytes of the LuaString to a PrintStream as if it were an ASCII * string, quoting and escaping control characters. - * + * * @param ps PrintStream to print to. */ public void printToStream(PrintStream ps) { diff --git a/luaj-core/src/main/java/org/luaj/vm2/LuaTable.java b/luaj-core/src/main/java/org/luaj/vm2/LuaTable.java index 3821f4c4..6f689024 100644 --- a/luaj-core/src/main/java/org/luaj/vm2/LuaTable.java +++ b/luaj-core/src/main/java/org/luaj/vm2/LuaTable.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 @@ -45,7 +45,7 @@ import java.util.Vector; * *

    * To iterate over key-value pairs from Java, use - * + * *

      *  {@code
      * LuaValue k = LuaValue.NIL;
    @@ -57,7 +57,7 @@ import java.util.Vector;
      *    process( k, v )
      * }}
      * 
    - * + * *

    * As with other types, {@link LuaTable} instances should be constructed via one * of the table constructor methods on {@link LuaValue}: @@ -73,7 +73,7 @@ import java.util.Vector; *

  • {@link LuaValue#tableOf(LuaValue[], LuaValue[], Varargs)} initialize * array and named parts
  • * - * + * * @see LuaValue */ public class LuaTable extends LuaValue implements Metatable { @@ -100,7 +100,7 @@ public class LuaTable extends LuaValue implements Metatable { /** * Construct table with preset capacity. - * + * * @param narray capacity of array part * @param nhash capacity of hash part */ @@ -110,16 +110,16 @@ public class LuaTable extends LuaValue implements Metatable { /** * Construct table with named and unnamed parts. - * + * * @param named Named elements in order * {@code key-a, value-a, key-b, value-b, ... } * @param unnamed Unnamed elements in order {@code value-1, value-2, ... } * @param lastarg Additional unnamed values beyond {@code unnamed.length} */ public LuaTable(LuaValue[] named, LuaValue[] unnamed, Varargs lastarg) { - int nn = (named != null? named.length: 0); - int nu = (unnamed != null? unnamed.length: 0); - int nl = (lastarg != null? lastarg.narg(): 0); + int nn = named != null? named.length: 0; + int nu = unnamed != null? unnamed.length: 0; + int nl = lastarg != null? lastarg.narg(): 0; presize(nu+nl, nn>>1); for (int i = 0; i < nu; i++) rawset(i+1, unnamed[i]); @@ -133,7 +133,7 @@ public class LuaTable extends LuaValue implements Metatable { /** * Construct table of unnamed elements. - * + * * @param varargs Unnamed elements in order {@code value-1, value-2, ... } */ public LuaTable(Varargs varargs) { @@ -142,7 +142,7 @@ public class LuaTable extends LuaValue implements Metatable { /** * Construct table of unnamed elements. - * + * * @param varargs Unnamed elements in order {@code value-1, value-2, ... } * @param firstarg the index in varargs of the first argument to include in * the table @@ -156,26 +156,32 @@ public class LuaTable extends LuaValue implements Metatable { set(i, varargs.arg(i+nskip)); } + @Override public int type() { return LuaValue.TTABLE; } + @Override public String typename() { return "table"; } + @Override public boolean istable() { return true; } + @Override public LuaTable checktable() { return this; } + @Override public LuaTable opttable(LuaTable defval) { return this; } + @Override public void presize(int narray) { if (narray > array.length) array = resize(array, 1< 0 && nhash < MIN_HASH_CAPACITY) nhash = MIN_HASH_CAPACITY; // Size of both parts must be a power of two. - array = (narray > 0? new LuaValue[1< 0? new Slot[1< 0? new LuaValue[1< 0? new Slot[1< 0 && key <= array.length) { LuaValue v = m_metatable == null? array[key-1]: m_metatable.arrayget(array, key-1); @@ -247,6 +258,7 @@ public class LuaTable extends LuaValue implements Metatable { return hashget(LuaInteger.valueOf(key)); } + @Override public LuaValue rawget(LuaValue key) { if (key.isinttype()) { int ikey = key.toint(); @@ -270,12 +282,14 @@ public class LuaTable extends LuaValue implements Metatable { return NIL; } + @Override public void set(int key, LuaValue value) { if (m_metatable == null || !rawget(key).isnil() || !settable(this, LuaInteger.valueOf(key), value)) rawset(key, value); } /** caller must ensure key is not nil */ + @Override public void set(LuaValue key, LuaValue value) { if (key == null || !key.isvalidkey() && !metatag(NEWINDEX).isfunction()) throw new LuaError("value ('" + key + "') can not be used as a table index"); @@ -283,12 +297,14 @@ public class LuaTable extends LuaValue implements Metatable { rawset(key, value); } + @Override public void rawset(int key, LuaValue value) { if (!arrayset(key, value)) hashset(LuaInteger.valueOf(key), value); } /** caller must ensure key is not nil */ + @Override public void rawset(LuaValue key, LuaValue value) { if (!key.isinttype() || !arrayset(key.toint(), value)) hashset(key, value); @@ -297,7 +313,7 @@ public class LuaTable extends LuaValue implements Metatable { /** Set an array element */ private boolean arrayset(int key, LuaValue value) { if (key > 0 && key <= array.length) { - array[key-1] = value.isnil()? null: (m_metatable != null? m_metatable.wrap(value): value); + array[key-1] = value.isnil()? null: m_metatable != null? m_metatable.wrap(value): value; return true; } return false; @@ -305,7 +321,7 @@ public class LuaTable extends LuaValue implements Metatable { /** * Remove the element at a position in a list-table - * + * * @param pos the position to remove * @return The removed item, or {@link #NONE} if not removed */ @@ -325,7 +341,7 @@ public class LuaTable extends LuaValue implements Metatable { /** * Insert an element at a position in a list-table - * + * * @param pos the position to remove * @param value The value to insert */ @@ -341,7 +357,7 @@ public class LuaTable extends LuaValue implements Metatable { /** * Concatenate the contents of a table efficiently, using {@link Buffer} - * + * * @param sep {@link LuaString} separater to apply between elements * @param i the first element index * @param j the last element index, inclusive @@ -359,6 +375,7 @@ public class LuaTable extends LuaValue implements Metatable { return sb.tostring(); } + @Override public int length() { if (m_metatable != null) { LuaValue len = len(); @@ -369,6 +386,7 @@ public class LuaTable extends LuaValue implements Metatable { return rawlen(); } + @Override public LuaValue len() { final LuaValue h = metatag(LEN); if (h.toboolean()) @@ -376,6 +394,7 @@ public class LuaTable extends LuaValue implements Metatable { return LuaInteger.valueOf(rawlen()); } + @Override public int rawlen() { int a = getArrayLength(); int n = a+1, m = 0; @@ -395,9 +414,10 @@ public class LuaTable extends LuaValue implements Metatable { /** * Get the next element after a particular key in the table - * + * * @return key,value or nil */ + @Override public Varargs next(LuaValue key) { int i = 0; do { @@ -458,9 +478,10 @@ public class LuaTable extends LuaValue implements Metatable { /** * Get the next element after a particular key in the contiguous array part * of a table - * + * * @return key,value or none */ + @Override public Varargs inext(LuaValue key) { int k = key.checkint()+1; LuaValue v = rawget(k); @@ -469,7 +490,7 @@ public class LuaTable extends LuaValue implements Metatable { /** * Set a hashtable value - * + * * @param key key to set * @param value value to set */ @@ -499,8 +520,8 @@ public class LuaTable extends LuaValue implements Metatable { } index = hashSlot(key); } - Slot entry = (m_metatable != null)? m_metatable.entry(key, value): defaultEntry(key, value); - hash[index] = (hash[index] != null)? hash[index].add(entry): entry; + Slot entry = m_metatable != null? m_metatable.entry(key, value): defaultEntry(key, value); + hash[index] = hash[index] != null? hash[index].add(entry): entry; ++hashEntries; } } @@ -515,7 +536,7 @@ public class LuaTable extends LuaValue implements Metatable { /** * Find the hashtable slot index to use. - * + * * @param key the key to look for * @param hashMask N-1 where N is the number of hash slots (must be power of * 2) @@ -536,7 +557,7 @@ public class LuaTable extends LuaValue implements Metatable { /** * Find the hashtable slot to use - * + * * @param key key to look for * @return slot to use */ @@ -564,8 +585,8 @@ public class LuaTable extends LuaValue implements Metatable { private int countHashKeys() { int keys = 0; - for (int i = 0; i < hash.length; ++i) { - for (Slot slot = hash[i]; slot != null; slot = slot.rest()) { + for (Slot element : hash) { + for (Slot slot = element; slot != null; slot = slot.rest()) { if (slot.first() != null) keys++; } @@ -710,7 +731,7 @@ public class LuaTable extends LuaValue implements Metatable { if (total*2 < 1<= (1<<(log-1))) { + } else if (keys >= 1< newArraySize)? 1: 0); // Make room for the new entry + final int newHashSize = hashEntries-movingToArray+(newKey < 0 || newKey > newArraySize? 1: 0); // Make room for the new entry final int oldCapacity = oldHash.length; final int newCapacity; final int newHashMask; if (newHashSize > 0) { // round up to next power of 2. - newCapacity = (newHashSize < MIN_HASH_CAPACITY)? MIN_HASH_CAPACITY: 1<= (long) Integer.MAX_VALUE) + if (len().tolong() >= Integer.MAX_VALUE) throw new LuaError("array too big: " + len().tolong()); if (m_metatable != null && m_metatable.useWeakValues()) { dropWeakArrayValues(); @@ -886,7 +908,7 @@ public class LuaTable extends LuaValue implements Metatable { /** * This may be deprecated in a future release. It is recommended to count * via iteration over next() instead - * + * * @return count of keys in the table */ public int keyCount() { @@ -901,7 +923,7 @@ public class LuaTable extends LuaValue implements Metatable { /** * This may be deprecated in a future release. It is recommended to use * next() instead - * + * * @return array of keys in the table */ public LuaValue[] keys() { @@ -919,8 +941,10 @@ public class LuaTable extends LuaValue implements Metatable { } // equality w/ metatable processing + @Override public LuaValue eq(LuaValue val) { return eq_b(val)? TRUE: FALSE; } + @Override public boolean eq_b(LuaValue val) { if (this == val) return true; @@ -1049,42 +1073,52 @@ public class LuaTable extends LuaValue implements Metatable { this.next = next; } + @Override public LuaValue key() { return entry.key(); } + @Override public int keyindex(int hashMask) { return entry.keyindex(hashMask); } + @Override public LuaValue value() { return entry.value(); } + @Override public Varargs toVarargs() { return entry.toVarargs(); } + @Override public StrongSlot first() { return entry; } + @Override public StrongSlot find(LuaValue key) { return entry.keyeq(key)? this: null; } + @Override public boolean keyeq(LuaValue key) { return entry.keyeq(key); } + @Override public Slot rest() { return next; } + @Override public int arraykey(int max) { return entry.arraykey(max); } + @Override public Slot set(StrongSlot target, LuaValue value) { if (target == this) { entry = entry.set(value); @@ -1094,10 +1128,12 @@ public class LuaTable extends LuaValue implements Metatable { } } + @Override public Slot add(Slot entry) { return setnext(next.add(entry)); } + @Override public Slot remove(StrongSlot target) { if (this == target) { return new DeadSlot(key(), next); @@ -1107,9 +1143,10 @@ public class LuaTable extends LuaValue implements Metatable { return this; } + @Override public Slot relink(Slot rest) { // This method is (only) called during rehash, so it must not change this.next. - return (rest != null)? new LinkSlot(entry, rest): (Slot) entry; + return rest != null? new LinkSlot(entry, rest): (Slot) entry; } // this method ensures that this.next is never set to null. @@ -1122,6 +1159,7 @@ public class LuaTable extends LuaValue implements Metatable { } } + @Override public String toString() { return entry + "; " + next; } @@ -1129,26 +1167,32 @@ public class LuaTable extends LuaValue implements Metatable { /** * Base class for regular entries. - * + * *

    * If the key may be an integer, the {@link #arraykey(int)} method must be * overridden to handle that case. */ static abstract class Entry extends Varargs implements StrongSlot { + @Override public abstract LuaValue key(); + @Override public abstract LuaValue value(); abstract Entry set(LuaValue value); + @Override public abstract boolean keyeq(LuaValue key); + @Override public abstract int keyindex(int hashMask); + @Override public int arraykey(int max) { return 0; } + @Override public LuaValue arg(int i) { switch (i) { case 1: @@ -1159,6 +1203,7 @@ public class LuaTable extends LuaValue implements Metatable { return NIL; } + @Override public int narg() { return 2; } @@ -1166,14 +1211,17 @@ public class LuaTable extends LuaValue implements Metatable { /** * Subclasses should redefine as "return this;" whenever possible. */ + @Override public Varargs toVarargs() { return varargsOf(key(), value()); } + @Override public LuaValue arg1() { return key(); } + @Override public Varargs subargs(int start) { switch (start) { case 1: @@ -1184,32 +1232,39 @@ public class LuaTable extends LuaValue implements Metatable { return NONE; } + @Override public StrongSlot first() { return this; } + @Override public Slot rest() { return null; } + @Override public StrongSlot find(LuaValue key) { return keyeq(key)? this: null; } + @Override public Slot set(StrongSlot target, LuaValue value) { return set(value); } + @Override public Slot add(Slot entry) { return new LinkSlot(this, entry); } + @Override public Slot remove(StrongSlot target) { return new DeadSlot(key(), null); } + @Override public Slot relink(Slot rest) { - return (rest != null)? new LinkSlot(this, rest): (Slot) this; + return rest != null? new LinkSlot(this, rest): (Slot) this; } } @@ -1222,27 +1277,33 @@ public class LuaTable extends LuaValue implements Metatable { this.value = value; } + @Override public LuaValue key() { return key; } + @Override public LuaValue value() { return value; } + @Override public Entry set(LuaValue value) { this.value = value; return this; } + @Override public Varargs toVarargs() { return this; } + @Override public int keyindex(int hashMask) { return hashSlot(key, hashMask); } + @Override public boolean keyeq(LuaValue key) { return key.raweq(this.key); } @@ -1257,27 +1318,33 @@ public class LuaTable extends LuaValue implements Metatable { this.value = value; } + @Override public LuaValue key() { return valueOf(key); } + @Override public int arraykey(int max) { - return (key >= 1 && key <= max)? key: 0; + return key >= 1 && key <= max? key: 0; } + @Override public LuaValue value() { return value; } + @Override public Entry set(LuaValue value) { this.value = value; return this; } + @Override public int keyindex(int mask) { return hashmod(LuaInteger.hashCode(key), mask); } + @Override public boolean keyeq(LuaValue key) { return key.raweq(this.key); } @@ -1296,14 +1363,17 @@ public class LuaTable extends LuaValue implements Metatable { this.value = value; } + @Override public LuaValue key() { return key; } + @Override public LuaValue value() { return valueOf(value); } + @Override public Entry set(LuaValue value) { if (value.type() == TNUMBER) { LuaValue n = value.tonumber(); @@ -1315,10 +1385,12 @@ public class LuaTable extends LuaValue implements Metatable { return new NormalEntry(this.key, value); } + @Override public int keyindex(int mask) { return hashSlot(key, mask); } + @Override public boolean keyeq(LuaValue key) { return key.raweq(this.key); } @@ -1342,34 +1414,41 @@ public class LuaTable extends LuaValue implements Metatable { return (LuaValue) (key instanceof WeakReference? ((WeakReference) key).get(): key); } + @Override public int keyindex(int hashMask) { // Not needed: this entry will be dropped during rehash. return 0; } + @Override public StrongSlot first() { return null; } + @Override public StrongSlot find(LuaValue key) { return null; } + @Override public boolean keyeq(LuaValue key) { LuaValue k = key(); return k != null && key.raweq(k); } + @Override public Slot rest() { return next; } + @Override public int arraykey(int max) { return -1; } + @Override public Slot set(StrongSlot target, LuaValue value) { - Slot next = (this.next != null)? this.next.set(target, value): null; + Slot next = this.next != null? this.next.set(target, value): null; if (key() != null) { // if key hasn't been garbage collected, it is still potentially a valid argument // to next(), so we can't drop this entry yet. @@ -1380,10 +1459,12 @@ public class LuaTable extends LuaValue implements Metatable { } } + @Override public Slot add(Slot newEntry) { - return (next != null)? next.add(newEntry): newEntry; + return next != null? next.add(newEntry): newEntry; } + @Override public Slot remove(StrongSlot target) { if (key() != null) { next = next.remove(target); @@ -1393,10 +1474,12 @@ public class LuaTable extends LuaValue implements Metatable { } } + @Override public Slot relink(Slot rest) { return rest; } + @Override public String toString() { StringBuffer buf = new StringBuffer(); buf.append(" * Operations are performed on values directly via their Java methods. For * example, the following code divides two numbers: - * + * *

      * {
      * 	@code
    @@ -47,7 +47,7 @@ package org.luaj.vm2;
      * 	LuaValue c = a.div(b);
      * }
      * 
    - * + * * Note that in this example, c will be a {@link LuaDouble}, but would be a * {@link LuaInteger} if the value of a were changed to 8, say. In general the * value of c in practice will vary depending on both the types and values of a @@ -55,7 +55,7 @@ package org.luaj.vm2; *

    * Field access and function calls are similar, with common overloads to * simplify Java usage: - * + * *

      * {
      * 	@code
    @@ -69,7 +69,7 @@ package org.luaj.vm2;
      * 

    * To supply variable arguments or get multiple return values, use * {@link #invoke(Varargs)} or {@link #invokemethod(LuaValue, Varargs)} methods: - * + * *

      * {
      * 	@code
    @@ -80,7 +80,7 @@ package org.luaj.vm2;
      * 
    *

    * To load and run a script, {@link LoadState} is used: - * + * *

      *  {@code
      * LoadState.load( new FileInputStream("main.lua"), "main.lua", globals ).call();
    @@ -88,13 +88,13 @@ package org.luaj.vm2;
      * 
    *

    * although {@code require} could also be used: - * + * *

      *  {@code
      * globals.get("require").call(LuaValue.valueOf("main"));
      * }
      * 
    - * + * * For this to work the file must be in the current directory, or in the class * path, dependening on the platform. See * {@link org.luaj.vm2.lib.jse.JsePlatform} and @@ -123,7 +123,7 @@ package org.luaj.vm2; * {@link #ADD}, {@link #SUB}, {@link #DIV}, {@link #MUL}, {@link #POW}, * {@link #MOD}, {@link #UNM}, {@link #LEN}, {@link #EQ}, {@link #LT}, * {@link #LE}, {@link #TOSTRING}, and {@link #CONCAT}. - * + * * @see org.luaj.vm2.lib.jse.JsePlatform * @see org.luaj.vm2.lib.jme.JmePlatform * @see LoadState @@ -135,13 +135,13 @@ abstract public class LuaValue extends Varargs { * Type enumeration constant for lua numbers that are ints, for * compatibility with lua 5.1 number patch only */ - public static final int TINT = (-2); + public static final int TINT = -2; /** * Type enumeration constant for lua values that have no type, for example * weak table entries */ - public static final int TNONE = (-1); + public static final int TNONE = -1; /** Type enumeration constant for lua nil */ public static final int TNIL = 0; @@ -181,7 +181,7 @@ abstract public class LuaValue extends Varargs { /** * String array constant containing names of each of the lua value types - * + * * @see #type() * @see #typename() */ @@ -290,7 +290,7 @@ abstract public class LuaValue extends Varargs { // type /** * Get the enumeration value for the type of this value. - * + * * @return value for this type, one of {@link #TNIL}, {@link #TBOOLEAN}, * {@link #TNUMBER}, {@link #TSTRING}, {@link #TTABLE}, * {@link #TFUNCTION}, {@link #TUSERDATA}, {@link #TTHREAD} @@ -301,7 +301,7 @@ abstract public class LuaValue extends Varargs { /** * Get the String name of the type of this value. *

    - * + * * @return name from type name list {@link #TYPE_NAMES} corresponding to the * type of this value: "nil", "boolean", "number", "string", * "table", "function", "userdata", "thread" @@ -311,7 +311,7 @@ abstract public class LuaValue extends Varargs { /** * Check if {@code this} is a {@code boolean} - * + * * @return true if this is a {@code boolean}, otherwise false * @see #isboolean() * @see #toboolean() @@ -324,7 +324,7 @@ abstract public class LuaValue extends Varargs { /** * Check if {@code this} is a {@code function} that is a closure, meaning * interprets lua bytecode for its execution - * + * * @return true if this is a {@code closure}, otherwise false * @see #isfunction() * @see #checkclosure() @@ -335,7 +335,7 @@ abstract public class LuaValue extends Varargs { /** * Check if {@code this} is a {@code function} - * + * * @return true if this is a {@code function}, otherwise false * @see #isclosure() * @see #checkfunction() @@ -347,7 +347,7 @@ abstract public class LuaValue extends Varargs { /** * Check if {@code this} is a {@code number} and is representable by java * int without rounding or truncation - * + * * @return true if this is a {@code number} meaning derives from * {@link LuaNumber} or derives from {@link LuaString} and is * convertible to a number, and can be represented by int, otherwise @@ -365,7 +365,7 @@ abstract public class LuaValue extends Varargs { * Check if {@code this} is a {@link LuaInteger} *

    * No attempt to convert from string will be made by this call. - * + * * @return true if this is a {@code LuaInteger}, otherwise false * @see #isint() * @see #isnumber() @@ -377,7 +377,7 @@ abstract public class LuaValue extends Varargs { /** * Check if {@code this} is a {@code number} and is representable by java * long without rounding or truncation - * + * * @return true if this is a {@code number} meaning derives from * {@link LuaNumber} or derives from {@link LuaString} and is * convertible to a number, and can be represented by long, @@ -391,7 +391,7 @@ abstract public class LuaValue extends Varargs { /** * Check if {@code this} is {@code #NIL} - * + * * @return true if this is {@code #NIL}, otherwise false * @see #NIL * @see #NONE @@ -405,7 +405,7 @@ abstract public class LuaValue extends Varargs { /** * Check if {@code this} is a {@code number} - * + * * @return true if this is a {@code number}, meaning derives from * {@link LuaNumber} or derives from {@link LuaString} and is * convertible to a number, otherwise false @@ -418,7 +418,7 @@ abstract public class LuaValue extends Varargs { /** * Check if {@code this} is a {@code string} - * + * * @return true if this is a {@code string}, meaning derives from * {@link LuaString} or {@link LuaNumber}, otherwise false * @see #tostring() @@ -430,7 +430,7 @@ abstract public class LuaValue extends Varargs { /** * Check if {@code this} is a {@code thread} - * + * * @return true if this is a {@code thread}, otherwise false * @see #checkthread() * @see #optthread(LuaThread) @@ -440,7 +440,7 @@ abstract public class LuaValue extends Varargs { /** * Check if {@code this} is a {@code table} - * + * * @return true if this is a {@code table}, otherwise false * @see #checktable() * @see #opttable(LuaTable) @@ -450,7 +450,7 @@ abstract public class LuaValue extends Varargs { /** * Check if {@code this} is a {@code userdata} - * + * * @return true if this is a {@code userdata}, otherwise false * @see #isuserdata(Class) * @see #touserdata() @@ -462,7 +462,7 @@ abstract public class LuaValue extends Varargs { /** * Check if {@code this} is a {@code userdata} of type {@code c} - * + * * @param c Class to test instance against * @return true if this is a {@code userdata} and the instance is assignable * to {@code c}, otherwise false @@ -477,7 +477,7 @@ abstract public class LuaValue extends Varargs { /** * Convert to boolean false if {@link #NIL} or {@link #FALSE}, true if * anything else - * + * * @return Value cast to byte if number or string convertible to number, * otherwise 0 * @see #optboolean(boolean) @@ -489,7 +489,7 @@ abstract public class LuaValue extends Varargs { /** * Convert to byte if numeric, or 0 if not. - * + * * @return Value cast to byte if number or string convertible to number, * otherwise 0 * @see #toint() @@ -502,7 +502,7 @@ abstract public class LuaValue extends Varargs { /** * Convert to char if numeric, or 0 if not. - * + * * @return Value cast to char if number or string convertible to number, * otherwise 0 * @see #toint() @@ -515,7 +515,7 @@ abstract public class LuaValue extends Varargs { /** * Convert to double if numeric, or 0 if not. - * + * * @return Value cast to double if number or string convertible to number, * otherwise 0 * @see #toint() @@ -533,7 +533,7 @@ abstract public class LuaValue extends Varargs { /** * Convert to float if numeric, or 0 if not. - * + * * @return Value cast to float if number or string convertible to number, * otherwise 0 * @see #toint() @@ -546,7 +546,7 @@ abstract public class LuaValue extends Varargs { /** * Convert to int if numeric, or 0 if not. - * + * * @return Value cast to int if number or string convertible to number, * otherwise 0 * @see #tobyte() @@ -564,7 +564,7 @@ abstract public class LuaValue extends Varargs { /** * Convert to long if numeric, or 0 if not. - * + * * @return Value cast to long if number or string convertible to number, * otherwise 0 * @see #isint() @@ -580,7 +580,7 @@ abstract public class LuaValue extends Varargs { /** * Convert to short if numeric, or 0 if not. - * + * * @return Value cast to short if number or string convertible to number, * otherwise 0 * @see #toint() @@ -593,7 +593,7 @@ abstract public class LuaValue extends Varargs { /** * Convert to human readable String for any type. - * + * * @return String for use by human readers based on type. * @see #tostring() * @see #optjstring(String) @@ -601,11 +601,12 @@ abstract public class LuaValue extends Varargs { * @see #isstring() * @see #TSTRING */ + @Override public String tojstring() { return typename() + ": " + Integer.toHexString(hashCode()); } /** * Convert to userdata instance, or null. - * + * * @return userdata instance if userdata, or null if not {@link LuaUserdata} * @see #optuserdata(Object) * @see #checkuserdata() @@ -616,7 +617,7 @@ abstract public class LuaValue extends Varargs { /** * Convert to userdata instance if specific type, or null. - * + * * @return userdata instance if is a userdata whose instance derives from * {@code c}, or null if not {@link LuaUserdata} * @see #optuserdata(Class,Object) @@ -628,7 +629,7 @@ abstract public class LuaValue extends Varargs { /** * Convert the value to a human readable string using {@link #tojstring()} - * + * * @return String value intended to be human readible. * @see #tostring() * @see #tojstring() @@ -636,6 +637,7 @@ abstract public class LuaValue extends Varargs { * @see #checkstring() * @see #toString() */ + @Override public String toString() { return tojstring(); } /** @@ -649,7 +651,7 @@ abstract public class LuaValue extends Varargs { * This allows values to be tested for their "numeric-ness" without the * penalty of throwing exceptions, nor the cost of converting the type and * creating storage for it. - * + * * @return {@code this} if it is a {@link LuaNumber} or {@link LuaString} * that can be converted to a number, otherwise {@link #NIL} * @see #tostring() @@ -669,7 +671,7 @@ abstract public class LuaValue extends Varargs { *

    * This allows values to be tested for their "string-ness" without the * penalty of throwing exceptions. - * + * * @return {@code this} if it is a {@link LuaString} or {@link LuaNumber}, * otherwise {@link #NIL} * @see #tonumber() @@ -682,7 +684,7 @@ abstract public class LuaValue extends Varargs { /** * Check that optional argument is a boolean and return its boolean value - * + * * @param defval boolean value to return if {@code this} is nil or none * @return {@code this} cast to boolean if a {@link LuaBoolean}, * {@code defval} if nil or none, throws {@link LuaError} otherwise @@ -699,7 +701,7 @@ abstract public class LuaValue extends Varargs { *

    * A {@link LuaClosure} is a {@link LuaFunction} that executes lua * byteccode. - * + * * @param defval {@link LuaClosure} to return if {@code this} is nil or none * @return {@code this} cast to {@link LuaClosure} if a function, * {@code defval} if nil or none, throws {@link LuaError} otherwise @@ -713,7 +715,7 @@ abstract public class LuaValue extends Varargs { /** * Check that optional argument is a number or string convertible to number * and return as double - * + * * @param defval double to return if {@code this} is nil or none * @return {@code this} cast to double if numeric, {@code defval} if nil or * none, throws {@link LuaError} otherwise @@ -735,7 +737,7 @@ abstract public class LuaValue extends Varargs { * A {@link LuaFunction} may either be a Java function that implements * functionality directly in Java, or a {@link LuaClosure} which is a * {@link LuaFunction} that executes lua bytecode. - * + * * @param defval {@link LuaFunction} to return if {@code this} is nil or * none * @return {@code this} cast to {@link LuaFunction} if a function, @@ -750,7 +752,7 @@ abstract public class LuaValue extends Varargs { /** * Check that optional argument is a number or string convertible to number * and return as int - * + * * @param defval int to return if {@code this} is nil or none * @return {@code this} cast to int if numeric, {@code defval} if nil or * none, throws {@link LuaError} otherwise @@ -769,7 +771,7 @@ abstract public class LuaValue extends Varargs { /** * Check that optional argument is a number or string convertible to number * and return as {@link LuaInteger} - * + * * @param defval {@link LuaInteger} to return if {@code this} is nil or none * @return {@code this} converted and wrapped in {@link LuaInteger} if * numeric, {@code defval} if nil or none, throws {@link LuaError} @@ -788,7 +790,7 @@ abstract public class LuaValue extends Varargs { /** * Check that optional argument is a number or string convertible to number * and return as long - * + * * @param defval long to return if {@code this} is nil or none * @return {@code this} cast to long if numeric, {@code defval} if nil or * none, throws {@link LuaError} otherwise @@ -806,7 +808,7 @@ abstract public class LuaValue extends Varargs { /** * Check that optional argument is a number or string convertible to number * and return as {@link LuaNumber} - * + * * @param defval {@link LuaNumber} to return if {@code this} is nil or none * @return {@code this} cast to {@link LuaNumber} if numeric, {@code defval} * if nil or none, throws {@link LuaError} otherwise @@ -825,7 +827,7 @@ abstract public class LuaValue extends Varargs { /** * Check that optional argument is a string or number and return as Java * String - * + * * @param defval {@link LuaString} to return if {@code this} is nil or none * @return {@code this} converted to String if a string or number, * {@code defval} if nil or none, throws {@link LuaError} if some @@ -842,7 +844,7 @@ abstract public class LuaValue extends Varargs { /** * Check that optional argument is a string or number and return as * {@link LuaString} - * + * * @param defval {@link LuaString} to return if {@code this} is nil or none * @return {@code this} converted to {@link LuaString} if a string or * number, {@code defval} if nil or none, throws {@link LuaError} if @@ -858,7 +860,7 @@ abstract public class LuaValue extends Varargs { /** * Check that optional argument is a table and return as {@link LuaTable} - * + * * @param defval {@link LuaTable} to return if {@code this} is nil or none * @return {@code this} cast to {@link LuaTable} if a table, {@code defval} * if nil or none, throws {@link LuaError} if some other type @@ -871,7 +873,7 @@ abstract public class LuaValue extends Varargs { /** * Check that optional argument is a thread and return as {@link LuaThread} - * + * * @param defval {@link LuaThread} to return if {@code this} is nil or none * @return {@code this} cast to {@link LuaTable} if a thread, {@code defval} * if nil or none, throws {@link LuaError} if some other type @@ -884,7 +886,7 @@ abstract public class LuaValue extends Varargs { /** * Check that optional argument is a userdata and return the Object instance - * + * * @param defval Object to return if {@code this} is nil or none * @return Object instance of the userdata if a {@link LuaUserdata}, * {@code defval} if nil or none, throws {@link LuaError} if some @@ -900,7 +902,7 @@ abstract public class LuaValue extends Varargs { /** * Check that optional argument is a userdata whose instance is of a type * and return the Object instance - * + * * @param c Class to test userdata instance against * @param defval Object to return if {@code this} is nil or none * @return Object instance of the userdata if a {@link LuaUserdata} and @@ -917,7 +919,7 @@ abstract public class LuaValue extends Varargs { /** * Perform argument check that this is not nil or none. - * + * * @param defval {@link LuaValue} to return if {@code this} is nil or none * @return {@code this} if not nil or none, else {@code defval} * @see #NIL @@ -932,7 +934,7 @@ abstract public class LuaValue extends Varargs { /** * Check that the value is a {@link LuaBoolean}, or throw {@link LuaError} * if not - * + * * @return boolean value for {@code this} if it is a {@link LuaBoolean} * @throws LuaError if not a {@link LuaBoolean} * @see #optboolean(boolean) @@ -946,7 +948,7 @@ abstract public class LuaValue extends Varargs { *

    * {@link LuaClosure} is a subclass of {@link LuaFunction} that interprets * lua bytecode. - * + * * @return {@code this} cast as {@link LuaClosure} * @throws LuaError if not a {@link LuaClosure} * @see #checkfunction() @@ -962,7 +964,7 @@ abstract public class LuaValue extends Varargs { *

    * Values that are {@link LuaNumber} and values that are {@link LuaString} * that can be converted to a number will be converted to double. - * + * * @return value cast to a double if numeric * @throws LuaError if not a {@link LuaNumber} or is a {@link LuaString} * that can't be converted to number @@ -980,7 +982,7 @@ abstract public class LuaValue extends Varargs { * A {@link LuaFunction} may either be a Java function that implements * functionality directly in Java, or a {@link LuaClosure} which is a * {@link LuaFunction} that executes lua bytecode. - * + * * @return {@code this} if it is a lua function or closure * @throws LuaError if not a function * @see #checkclosure() @@ -993,7 +995,7 @@ abstract public class LuaValue extends Varargs { *

    * {@link Globals} are a special {@link LuaTable} that establish the default * global environment. - * + * * @return {@code this} if if an instance fof {@link Globals} * @throws LuaError if not a {@link Globals} instance. */ @@ -1006,7 +1008,7 @@ abstract public class LuaValue extends Varargs { * Values that are {@link LuaNumber} will be cast to int and may lose * precision. Values that are {@link LuaString} that can be converted to a * number will be converted, then cast to int, so may also lose precision. - * + * * @return value cast to a int if numeric * @throws LuaError if not a {@link LuaNumber} or is a {@link LuaString} * that can't be converted to number @@ -1025,7 +1027,7 @@ abstract public class LuaValue extends Varargs { * Values that are {@link LuaNumber} will be cast to int and may lose * precision. Values that are {@link LuaString} that can be converted to a * number will be converted, then cast to int, so may also lose precision. - * + * * @return value cast to a int and wrapped in {@link LuaInteger} if numeric * @throws LuaError if not a {@link LuaNumber} or is a {@link LuaString} * that can't be converted to number @@ -1044,7 +1046,7 @@ abstract public class LuaValue extends Varargs { * Values that are {@link LuaNumber} will be cast to long and may lose * precision. Values that are {@link LuaString} that can be converted to a * number will be converted, then cast to long, so may also lose precision. - * + * * @return value cast to a long if numeric * @throws LuaError if not a {@link LuaNumber} or is a {@link LuaString} * that can't be converted to number @@ -1062,7 +1064,7 @@ abstract public class LuaValue extends Varargs { *

    * Values that are {@link LuaString} that can be converted to a number will * be converted and returned. - * + * * @return value as a {@link LuaNumber} if numeric * @throws LuaError if not a {@link LuaNumber} or is a {@link LuaString} * that can't be converted to number @@ -1081,7 +1083,7 @@ abstract public class LuaValue extends Varargs { *

    * Values that are {@link LuaString} that can be converted to a number will * be converted and returned. - * + * * @param msg String message to supply if conversion fails * @return value as a {@link LuaNumber} if numeric * @throws LuaError if not a {@link LuaNumber} or is a {@link LuaString} @@ -1101,7 +1103,7 @@ abstract public class LuaValue extends Varargs { * The string representations here will roughly match what is produced by * the C lua distribution, however hash codes have no relationship, and * there may be differences in number formatting. - * + * * @return String representation of the value * @see #checkstring() * @see #optjstring(String) @@ -1117,7 +1119,7 @@ abstract public class LuaValue extends Varargs { * In lua all numbers are strings, so this will succeed for anything that * derives from {@link LuaString} or {@link LuaNumber}. Numbers will be * converted to {@link LuaString}. - * + * * @return {@link LuaString} representation of the value if it is a * {@link LuaString} or {@link LuaNumber} * @throws LuaError if {@code this} is not a {@link LuaTable} @@ -1132,7 +1134,7 @@ abstract public class LuaValue extends Varargs { /** * Check that this is a {@link LuaTable}, or throw {@link LuaError} if it is * not - * + * * @return {@code this} if it is a {@link LuaTable} * @throws LuaError if {@code this} is not a {@link LuaTable} * @see #istable() @@ -1144,7 +1146,7 @@ abstract public class LuaValue extends Varargs { /** * Check that this is a {@link LuaThread}, or throw {@link LuaError} if it * is not - * + * * @return {@code this} if it is a {@link LuaThread} * @throws LuaError if {@code this} is not a {@link LuaThread} * @see #isthread() @@ -1156,7 +1158,7 @@ abstract public class LuaValue extends Varargs { /** * Check that this is a {@link LuaUserdata}, or throw {@link LuaError} if it * is not - * + * * @return {@code this} if it is a {@link LuaUserdata} * @throws LuaError if {@code this} is not a {@link LuaUserdata} * @see #isuserdata() @@ -1169,7 +1171,7 @@ abstract public class LuaValue extends Varargs { /** * Check that this is a {@link LuaUserdata}, or throw {@link LuaError} if it * is not - * + * * @return {@code this} if it is a {@link LuaUserdata} * @throws LuaError if {@code this} is not a {@link LuaUserdata} * @see #isuserdata(Class) @@ -1182,7 +1184,7 @@ abstract public class LuaValue extends Varargs { /** * Check that this is not the value {@link #NIL}, or throw {@link LuaError} * if it is - * + * * @return {@code this} if it is not {@link #NIL} * @throws LuaError if {@code this} is {@link #NIL} * @see #optvalue(LuaValue) @@ -1191,7 +1193,7 @@ abstract public class LuaValue extends Varargs { /** * Return true if this is a valid key in a table index operation. - * + * * @return true if valid as a table key, otherwise false * @see #isnil() * @see #isinttype() @@ -1200,7 +1202,7 @@ abstract public class LuaValue extends Varargs { /** * Throw a {@link LuaError} with a particular message - * + * * @param message String providing message details * @throws LuaError in all cases */ @@ -1210,7 +1212,7 @@ abstract public class LuaValue extends Varargs { * Assert a condition is true, or throw a {@link LuaError} if not Returns no * value when b is true, throws {@link #error(String)} with {@code msg} as * argument and does not return if b is false. - * + * * @param b condition to test * @param msg String message to produce on failure * @throws LuaError if b is not true @@ -1223,7 +1225,7 @@ abstract public class LuaValue extends Varargs { /** * Throw a {@link LuaError} indicating an invalid argument was supplied to a * function - * + * * @param expected String naming the type that was expected * @throws LuaError in all cases */ @@ -1234,7 +1236,7 @@ abstract public class LuaValue extends Varargs { /** * Throw a {@link LuaError} indicating an invalid argument was supplied to a * function - * + * * @param iarg index of the argument that was invalid, first index is 1 * @param msg String providing information about the invalid argument * @throws LuaError in all cases @@ -1246,7 +1248,7 @@ abstract public class LuaValue extends Varargs { /** * Throw a {@link LuaError} indicating an invalid type was supplied to a * function - * + * * @param expected String naming the type that was expected * @throws LuaError in all cases */ @@ -1254,7 +1256,7 @@ abstract public class LuaValue extends Varargs { /** * Throw a {@link LuaError} indicating an operation is not implemented - * + * * @throws LuaError in all cases */ protected LuaValue unimplemented(String fun) { @@ -1264,7 +1266,7 @@ abstract public class LuaValue extends Varargs { /** * Throw a {@link LuaError} indicating an illegal operation occurred, * typically involved in managing weak references - * + * * @throws LuaError in all cases */ protected LuaValue illegal(String op, String typename) { @@ -1274,7 +1276,7 @@ abstract public class LuaValue extends Varargs { /** * Throw a {@link LuaError} based on the len operator, typically due to an * invalid operand type - * + * * @throws LuaError in all cases */ protected LuaValue lenerror() { throw new LuaError("attempt to get length of " + typename()); } @@ -1282,7 +1284,7 @@ abstract public class LuaValue extends Varargs { /** * Throw a {@link LuaError} based on an arithmetic error such as add, or * pow, typically due to an invalid operand type - * + * * @throws LuaError in all cases */ protected LuaValue aritherror() { throw new LuaError("attempt to perform arithmetic on " + typename()); } @@ -1290,7 +1292,7 @@ abstract public class LuaValue extends Varargs { /** * Throw a {@link LuaError} based on an arithmetic error such as add, or * pow, typically due to an invalid operand type - * + * * @param fun String description of the function that was attempted * @throws LuaError in all cases */ @@ -1301,7 +1303,7 @@ abstract public class LuaValue extends Varargs { /** * Throw a {@link LuaError} based on a comparison error such as greater-than * or less-than, typically due to an invalid operand type - * + * * @param rhs String description of what was on the right-hand-side of the * comparison that resulted in the error. * @throws LuaError in all cases @@ -1313,7 +1315,7 @@ abstract public class LuaValue extends Varargs { /** * Throw a {@link LuaError} based on a comparison error such as greater-than * or less-than, typically due to an invalid operand type - * + * * @param rhs Right-hand-side of the comparison that resulted in the error. * @throws LuaError in all cases */ @@ -1323,7 +1325,7 @@ abstract public class LuaValue extends Varargs { /** * Get a value in a table including metatag processing using {@link #INDEX}. - * + * * @param key the key to look up, must not be {@link #NIL} or null * @return {@link LuaValue} for that key, or {@link #NIL} if not found and * no metatag @@ -1337,7 +1339,7 @@ abstract public class LuaValue extends Varargs { /** * Get a value in a table including metatag processing using {@link #INDEX}. - * + * * @param key the key to look up * @return {@link LuaValue} for that key, or {@link #NIL} if not found * @throws LuaError if {@code this} is not a table, or there is no @@ -1349,7 +1351,7 @@ abstract public class LuaValue extends Varargs { /** * Get a value in a table including metatag processing using {@link #INDEX}. - * + * * @param key the key to look up, must not be null * @return {@link LuaValue} for that key, or {@link #NIL} if not found * @throws LuaError if {@code this} is not a table, or there is no @@ -1362,7 +1364,7 @@ abstract public class LuaValue extends Varargs { /** * Set a value in a table without metatag processing using * {@link #NEWINDEX}. - * + * * @param key the key to use, must not be {@link #NIL} or null * @param value the value to use, can be {@link #NIL}, must not be null * @throws LuaError if {@code this} is not a table, or key is {@link #NIL}, @@ -1373,7 +1375,7 @@ abstract public class LuaValue extends Varargs { /** * Set a value in a table without metatag processing using * {@link #NEWINDEX}. - * + * * @param key the key to use * @param value the value to use, can be {@link #NIL}, must not be null * @throws LuaError if {@code this} is not a table, or there is no @@ -1384,7 +1386,7 @@ abstract public class LuaValue extends Varargs { /** * Set a value in a table without metatag processing using * {@link #NEWINDEX}. - * + * * @param key the key to use * @param value the value to use, must not be null * @throws LuaError if {@code this} is not a table, or there is no @@ -1395,7 +1397,7 @@ abstract public class LuaValue extends Varargs { /** * Set a value in a table without metatag processing using * {@link #NEWINDEX}. - * + * * @param key the key to use, must not be {@link #NIL} or null * @param value the value to use, can be {@link #NIL}, must not be null * @throws LuaError if {@code this} is not a table, or there is no @@ -1406,7 +1408,7 @@ abstract public class LuaValue extends Varargs { /** * Set a value in a table without metatag processing using * {@link #NEWINDEX}. - * + * * @param key the key to use, must not be null * @param value the value to use * @throws LuaError if {@code this} is not a table, or there is no @@ -1417,7 +1419,7 @@ abstract public class LuaValue extends Varargs { /** * Set a value in a table without metatag processing using * {@link #NEWINDEX}. - * + * * @param key the key to use, must not be null * @param value the value to use * @throws LuaError if {@code this} is not a table, or there is no @@ -1428,7 +1430,7 @@ abstract public class LuaValue extends Varargs { /** * Set a value in a table without metatag processing using * {@link #NEWINDEX}. - * + * * @param key the key to use, must not be null * @param value the value to use, must not be null * @throws LuaError if {@code this} is not a table, or there is no @@ -1438,7 +1440,7 @@ abstract public class LuaValue extends Varargs { /** * Get a value in a table without metatag processing. - * + * * @param key the key to look up, must not be {@link #NIL} or null * @return {@link LuaValue} for that key, or {@link #NIL} if not found * @throws LuaError if {@code this} is not a table, or key is {@link #NIL} @@ -1447,7 +1449,7 @@ abstract public class LuaValue extends Varargs { /** * Get a value in a table without metatag processing. - * + * * @param key the key to look up * @return {@link LuaValue} for that key, or {@link #NIL} if not found * @throws LuaError if {@code this} is not a table @@ -1456,7 +1458,7 @@ abstract public class LuaValue extends Varargs { /** * Get a value in a table without metatag processing. - * + * * @param key the key to look up, must not be null * @return {@link LuaValue} for that key, or {@link #NIL} if not found * @throws LuaError if {@code this} is not a table @@ -1465,7 +1467,7 @@ abstract public class LuaValue extends Varargs { /** * Set a value in a table without metatag processing. - * + * * @param key the key to use, must not be {@link #NIL} or null * @param value the value to use, can be {@link #NIL}, must not be null * @throws LuaError if {@code this} is not a table, or key is {@link #NIL} @@ -1474,7 +1476,7 @@ abstract public class LuaValue extends Varargs { /** * Set a value in a table without metatag processing. - * + * * @param key the key to use * @param value the value to use, can be {@link #NIL}, must not be null * @throws LuaError if {@code this} is not a table @@ -1483,7 +1485,7 @@ abstract public class LuaValue extends Varargs { /** * Set a value in a table without metatag processing. - * + * * @param key the key to use * @param value the value to use, can be {@link #NIL}, must not be null * @throws LuaError if {@code this} is not a table @@ -1492,7 +1494,7 @@ abstract public class LuaValue extends Varargs { /** * Set a value in a table without metatag processing. - * + * * @param key the key to use, must not be null * @param value the value to use, can be {@link #NIL}, must not be null * @throws LuaError if {@code this} is not a table @@ -1501,7 +1503,7 @@ abstract public class LuaValue extends Varargs { /** * Set a value in a table without metatag processing. - * + * * @param key the key to use, must not be null * @param value the value to use * @throws LuaError if {@code this} is not a table @@ -1510,7 +1512,7 @@ abstract public class LuaValue extends Varargs { /** * Set a value in a table without metatag processing. - * + * * @param key the key to use, must not be null * @param value the value to use * @throws LuaError if {@code this} is not a table @@ -1519,7 +1521,7 @@ abstract public class LuaValue extends Varargs { /** * Set a value in a table without metatag processing. - * + * * @param key the key to use, must not be null * @param value the value to use, must not be null * @throws LuaError if {@code this} is not a table @@ -1530,7 +1532,7 @@ abstract public class LuaValue extends Varargs { * Set list values in a table without invoking metatag processing *

    * Primarily used internally in response to a SETLIST bytecode. - * + * * @param key0 the first key to set in the table * @param values the list of values to set * @throws LuaError if this is not a table. @@ -1544,7 +1546,7 @@ abstract public class LuaValue extends Varargs { * Preallocate the array part of a table to be a certain size, *

    * Primarily used internally in response to a SETLIST bytecode. - * + * * @param i the number of array slots to preallocate in the table. * @throws LuaError if this is not a table. */ @@ -1556,7 +1558,7 @@ abstract public class LuaValue extends Varargs { * table. *

    * To iterate over all key-value pairs in a table you can use - * + * *

     	 *  {@code
     	 * LuaValue k = LuaValue.NIL;
    @@ -1568,7 +1570,7 @@ abstract public class LuaValue extends Varargs {
     	 *    process( k, v )
     	 * }}
     	 * 
    - * + * * @param index {@link LuaInteger} value identifying a key to start from, or * {@link #NIL} to start at the beginning * @return {@link Varargs} containing {key,value} for the next entry, or @@ -1590,7 +1592,7 @@ abstract public class LuaValue extends Varargs { * table. *

    * To iterate over integer keys in a table you can use - * + * *

     	 *  {@code
     	 *   LuaValue k = LuaValue.NIL;
    @@ -1603,7 +1605,7 @@ abstract public class LuaValue extends Varargs {
     	 *   }
     	 * }
     	 * 
    - * + * * @param index {@link LuaInteger} value identifying a key to start from, or * {@link #NIL} to start at the beginning * @return {@link Varargs} containing {@code (key,value)} for the next @@ -1624,17 +1626,20 @@ abstract public class LuaValue extends Varargs { * modname, and this Globals as the environment. This is normally used to * iniitalize the library instance and which may install itself into these * globals. - * + * * @param library The callable {@link LuaValue} to load into {@code this} * @return {@link LuaValue} returned by the initialization call. */ public LuaValue load(LuaValue library) { return library.call(EMPTYSTRING, this); } // varargs references + @Override public LuaValue arg(int index) { return index == 1? this: NIL; } - public int narg() { return 1; }; + @Override + public int narg() { return 1; } + @Override public LuaValue arg1() { return this; } /** @@ -1643,7 +1648,7 @@ abstract public class LuaValue extends Varargs { * For {@link LuaTable} and {@link LuaUserdata} instances, the metatable * returned is this instance metatable. For all other types, the class * metatable value will be returned. - * + * * @return metatable, or null if it there is none * @see LuaBoolean#s_metatable * @see LuaNumber#s_metatable @@ -1659,7 +1664,7 @@ abstract public class LuaValue extends Varargs { * For {@link LuaTable} and {@link LuaUserdata} instances, the metatable is * per instance. For all other types, there is one metatable per type that * can be set directly from java - * + * * @param metatable {@link LuaValue} instance to serve as the metatable, or * null to reset it. * @return {@code this} to allow chaining of Java function calls @@ -1684,7 +1689,7 @@ abstract public class LuaValue extends Varargs { *

    * To call {@code this} as a method call, use {@link #method(LuaValue)} * instead. - * + * * @return First return value {@code (this())}, or {@link #NIL} if there * were none. * @throws LuaError if not a function and {@link #CALL} is not defined, or @@ -1712,7 +1717,7 @@ abstract public class LuaValue extends Varargs { *

    * To call {@code this} as a method call, use {@link #method(LuaValue)} * instead. - * + * * @param arg First argument to supply to the called function * @return First return value {@code (this(arg))}, or {@link #NIL} if there * were none. @@ -1731,7 +1736,7 @@ abstract public class LuaValue extends Varargs { /** * Convenience function which calls a luavalue with a single, string * argument. - * + * * @param arg String argument to the function. This will be converted to a * LuaString. * @return return value of the invocation. @@ -1752,7 +1757,7 @@ abstract public class LuaValue extends Varargs { *

    * To call {@code this} as a method call, use {@link #method(LuaValue)} * instead. - * + * * @param arg1 First argument to supply to the called function * @param arg2 Second argument to supply to the called function * @return First return value {@code (this(arg1,arg2))}, or {@link #NIL} if @@ -1782,7 +1787,7 @@ abstract public class LuaValue extends Varargs { *

    * To call {@code this} as a method call, use {@link #method(LuaValue)} * instead. - * + * * @param arg1 First argument to supply to the called function * @param arg2 Second argument to supply to the called function * @param arg3 Second argument to supply to the called function @@ -1815,7 +1820,7 @@ abstract public class LuaValue extends Varargs { * returned. To get multiple values, use {@link #invoke()} instead. *

    * To call {@code this} as a plain call, use {@link #call()} instead. - * + * * @param name Name of the method to look up for invocation * @return All values returned from {@code this:name()} as a {@link Varargs} * instance @@ -1843,7 +1848,7 @@ abstract public class LuaValue extends Varargs { * returned. To get multiple values, use {@link #invoke()} instead. *

    * To call {@code this} as a plain call, use {@link #call()} instead. - * + * * @param name Name of the method to look up for invocation * @return All values returned from {@code this:name()} as a {@link Varargs} * instance @@ -1872,7 +1877,7 @@ abstract public class LuaValue extends Varargs { *

    * To call {@code this} as a plain call, use {@link #call(LuaValue)} * instead. - * + * * @param name Name of the method to look up for invocation * @param arg Argument to supply to the method * @return All values returned from {@code this:name(arg)} as a @@ -1902,7 +1907,7 @@ abstract public class LuaValue extends Varargs { *

    * To call {@code this} as a plain call, use {@link #call(LuaValue)} * instead. - * + * * @param name Name of the method to look up for invocation * @param arg Argument to supply to the method * @return All values returned from {@code this:name(arg)} as a @@ -1932,7 +1937,7 @@ abstract public class LuaValue extends Varargs { *

    * To call {@code this} as a plain call, use * {@link #call(LuaValue,LuaValue)} instead. - * + * * @param name Name of the method to look up for invocation * @param arg1 First argument to supply to the method * @param arg2 Second argument to supply to the method @@ -1964,7 +1969,7 @@ abstract public class LuaValue extends Varargs { *

    * To call {@code this} as a plain call, use * {@link #call(LuaValue,LuaValue)} instead. - * + * * @param name Name of the method to look up for invocation * @param arg1 First argument to supply to the method * @param arg2 Second argument to supply to the method @@ -1993,7 +1998,7 @@ abstract public class LuaValue extends Varargs { *

    * To call {@code this} as a method call, use * {@link #invokemethod(LuaValue)} instead. - * + * * @return All return values as a {@link Varargs} instance. * @throws LuaError if not a function and {@link #CALL} is not defined, or * the invoked function throws a {@link LuaError} or the @@ -2016,7 +2021,7 @@ abstract public class LuaValue extends Varargs { *

    * To call {@code this} as a method call, use * {@link #invokemethod(LuaValue)} instead. - * + * * @param args Varargs containing the arguments to supply to the called * function * @return All return values as a {@link Varargs} instance. @@ -2043,7 +2048,7 @@ abstract public class LuaValue extends Varargs { *

    * To call {@code this} as a method call, use * {@link #invokemethod(LuaValue,Varargs)} instead. - * + * * @param arg The first argument to supply to the called function * @param varargs Varargs containing the remaining arguments to supply to * the called function @@ -2070,7 +2075,7 @@ abstract public class LuaValue extends Varargs { *

    * To call {@code this} as a method call, use * {@link #invokemethod(LuaValue,Varargs)} instead. - * + * * @param arg1 The first argument to supply to the called function * @param arg2 The second argument to supply to the called function * @param varargs Varargs containing the remaining arguments to supply to @@ -2100,7 +2105,7 @@ abstract public class LuaValue extends Varargs { *

    * To call {@code this} as a method call, use * {@link #invokemethod(LuaValue,Varargs)} instead. - * + * * @param args Array of arguments to supply to the called function * @return All return values as a {@link Varargs} instance. * @throws LuaError if not a function and {@link #CALL} is not defined, or @@ -2125,7 +2130,7 @@ abstract public class LuaValue extends Varargs { *

    * To call {@code this} as a method call, use * {@link #invokemethod(LuaValue,Varargs)} instead. - * + * * @param args Array of arguments to supply to the called function * @param varargs Varargs containing additional arguments to supply to the * called function @@ -2155,7 +2160,7 @@ abstract public class LuaValue extends Varargs { * To get a particular return value, us {@link Varargs#arg(int)} *

    * To call {@code this} as a plain call, use {@link #invoke()} instead. - * + * * @param name Name of the method to look up for invocation * @return All values returned from {@code this:name()} as a {@link Varargs} * instance @@ -2185,7 +2190,7 @@ abstract public class LuaValue extends Varargs { * To get a particular return value, us {@link Varargs#arg(int)} *

    * To call {@code this} as a plain call, use {@link #invoke()} instead. - * + * * @param name Name of the method to look up for invocation * @return All values returned from {@code this:name()} as a {@link Varargs} * instance @@ -2216,7 +2221,7 @@ abstract public class LuaValue extends Varargs { *

    * To call {@code this} as a plain call, use {@link #invoke(Varargs)} * instead. - * + * * @param name Name of the method to look up for invocation * @param args {@link Varargs} containing arguments to supply to the called * function after {@code this} @@ -2249,7 +2254,7 @@ abstract public class LuaValue extends Varargs { *

    * To call {@code this} as a plain call, use {@link #invoke(Varargs)} * instead. - * + * * @param name Name of the method to look up for invocation * @param args {@link Varargs} containing arguments to supply to the called * function after {@code this} @@ -2282,7 +2287,7 @@ abstract public class LuaValue extends Varargs { *

    * To call {@code this} as a plain call, use {@link #invoke(Varargs)} * instead. - * + * * @param name Name of the method to look up for invocation * @param args Array of {@link LuaValue} containing arguments to supply to * the called function after {@code this} @@ -2318,7 +2323,7 @@ abstract public class LuaValue extends Varargs { *

    * To call {@code this} as a plain call, use {@link #invoke(Varargs)} * instead. - * + * * @param name Name of the method to look up for invocation * @param args Array of {@link LuaValue} containing arguments to supply to * the called function after {@code this} @@ -2343,7 +2348,7 @@ abstract public class LuaValue extends Varargs { /** * Get the metatag value for the {@link #CALL} metatag, if it exists. - * + * * @return {@link LuaValue} value if metatag is defined * @throws LuaError if {@link #CALL} metatag is not defined. */ @@ -2354,7 +2359,7 @@ abstract public class LuaValue extends Varargs { /** * Unary not: return inverse boolean value {@code (~this)} as defined by lua * not operator - * + * * @return {@link #TRUE} if {@link #NIL} or {@link #FALSE}, otherwise * {@link #FALSE} */ @@ -2363,7 +2368,7 @@ abstract public class LuaValue extends Varargs { /** * Unary minus: return negative value {@code (-this)} as defined by lua * unary minus operator - * + * * @return boolean inverse as {@link LuaBoolean} if boolean or nil, numeric * inverse as {@link LuaNumber} if numeric, or metatag processing * result if {@link #UNM} metatag is defined @@ -2375,7 +2380,7 @@ abstract public class LuaValue extends Varargs { /** * Length operator: return lua length of object {@code (#this)} including * metatag processing as java int - * + * * @return length as defined by the lua # operator or metatag processing * result * @throws LuaError if {@code this} is not a table or string, and has no @@ -2386,7 +2391,7 @@ abstract public class LuaValue extends Varargs { /** * Length operator: return lua length of object {@code (#this)} including * metatag processing as java int - * + * * @return length as defined by the lua # operator or metatag processing * result converted to java int using {@link #toint()} * @throws LuaError if {@code this} is not a table or string, and has no @@ -2396,19 +2401,20 @@ abstract public class LuaValue extends Varargs { /** * Get raw length of table or string without metatag processing. - * + * * @return the length of the table or string. * @throws LuaError if {@code this} is not a table or string. */ public int rawlen() { typerror("table or string"); return 0; } // object equality, used for key comparison + @Override public boolean equals(Object obj) { return this == obj; } /** * Equals: Perform equality comparison with another value including metatag * processing using {@link #EQ}. - * + * * @param val The value to compare with. * @return {@link #TRUE} if values are comparable and {@code (this == rhs)}, * {@link #FALSE} if comparable but not equal, {@link LuaValue} if @@ -2424,7 +2430,7 @@ abstract public class LuaValue extends Varargs { /** * Equals: Perform equality comparison with another value including metatag * processing using {@link #EQ}, and return java boolean - * + * * @param val The value to compare with. * @return true if values are comparable and {@code (this == rhs)}, false if * comparable but not equal, result converted to java boolean if @@ -2440,7 +2446,7 @@ abstract public class LuaValue extends Varargs { /** * Notquals: Perform inequality comparison with another value including * metatag processing using {@link #EQ}. - * + * * @param val The value to compare with. * @return {@link #TRUE} if values are comparable and {@code (this != rhs)}, * {@link #FALSE} if comparable but equal, inverse of @@ -2456,7 +2462,7 @@ abstract public class LuaValue extends Varargs { /** * Notquals: Perform inequality comparison with another value including * metatag processing using {@link #EQ}. - * + * * @param val The value to compare with. * @return true if values are comparable and {@code (this != rhs)}, false if * comparable but equal, inverse of result converted to boolean if @@ -2471,7 +2477,7 @@ abstract public class LuaValue extends Varargs { /** * Equals: Perform direct equality comparison with another value without * metatag processing. - * + * * @param val The value to compare with. * @return true if {@code (this == rhs)}, false otherwise * @see #eq(LuaValue) @@ -2486,7 +2492,7 @@ abstract public class LuaValue extends Varargs { /** * Equals: Perform direct equality comparison with a {@link LuaUserdata} * value without metatag processing. - * + * * @param val The {@link LuaUserdata} to compare with. * @return true if {@code this} is userdata and their metatables are the * same using == and their instances are equal using @@ -2499,7 +2505,7 @@ abstract public class LuaValue extends Varargs { /** * Equals: Perform direct equality comparison with a {@link LuaString} value * without metatag processing. - * + * * @param val The {@link LuaString} to compare with. * @return true if {@code this} is a {@link LuaString} and their byte * sequences match, otherwise false @@ -2509,7 +2515,7 @@ abstract public class LuaValue extends Varargs { /** * Equals: Perform direct equality comparison with a double value without * metatag processing. - * + * * @param val The double value to compare with. * @return true if {@code this} is a {@link LuaNumber} whose value equals * val, otherwise false @@ -2519,7 +2525,7 @@ abstract public class LuaValue extends Varargs { /** * Equals: Perform direct equality comparison with a int value without * metatag processing. - * + * * @param val The double value to compare with. * @return true if {@code this} is a {@link LuaNumber} whose value equals * val, otherwise false @@ -2528,7 +2534,7 @@ abstract public class LuaValue extends Varargs { /** * Perform equality testing metatag processing - * + * * @param lhs left-hand-side of equality expression * @param lhsmt metatag value for left-hand-side * @param rhs right-hand-side of equality expression @@ -2552,7 +2558,7 @@ abstract public class LuaValue extends Varargs { *

    * Each operand must derive from {@link LuaNumber} or derive from * {@link LuaString} and be convertible to a number - * + * * @param rhs The right-hand-side value to perform the add with * @return value of {@code (this + rhs)} if both are numeric, or * {@link LuaValue} if metatag processing occurs @@ -2569,7 +2575,7 @@ abstract public class LuaValue extends Varargs { *

    * {@code this} must derive from {@link LuaNumber} or derive from * {@link LuaString} and be convertible to a number - * + * * @param rhs The right-hand-side value to perform the add with * @return value of {@code (this + rhs)} if this is numeric * @throws LuaError if {@code this} is not a number or string convertible to @@ -2584,7 +2590,7 @@ abstract public class LuaValue extends Varargs { *

    * {@code this} must derive from {@link LuaNumber} or derive from * {@link LuaString} and be convertible to a number - * + * * @param rhs The right-hand-side value to perform the add with * @return value of {@code (this + rhs)} if this is numeric * @throws LuaError if {@code this} is not a number or string convertible to @@ -2599,7 +2605,7 @@ abstract public class LuaValue extends Varargs { *

    * Each operand must derive from {@link LuaNumber} or derive from * {@link LuaString} and be convertible to a number - * + * * @param rhs The right-hand-side value to perform the subtract with * @return value of {@code (this - rhs)} if both are numeric, or * {@link LuaValue} if metatag processing occurs @@ -2616,7 +2622,7 @@ abstract public class LuaValue extends Varargs { *

    * {@code this} must derive from {@link LuaNumber} or derive from * {@link LuaString} and be convertible to a number - * + * * @param rhs The right-hand-side value to perform the subtract with * @return value of {@code (this - rhs)} if this is numeric * @throws LuaError if {@code this} is not a number or string convertible to @@ -2631,7 +2637,7 @@ abstract public class LuaValue extends Varargs { *

    * {@code this} must derive from {@link LuaNumber} or derive from * {@link LuaString} and be convertible to a number - * + * * @param rhs The right-hand-side value to perform the subtract with * @return value of {@code (this - rhs)} if this is numeric * @throws LuaError if {@code this} is not a number or string convertible to @@ -2646,7 +2652,7 @@ abstract public class LuaValue extends Varargs { *

    * {@code this} must derive from {@link LuaNumber} or derive from * {@link LuaString} and be convertible to a number - * + * * @param lhs The left-hand-side value from which to perform the subtraction * @return value of {@code (lhs - this)} if this is numeric * @throws LuaError if {@code this} is not a number or string convertible to @@ -2665,7 +2671,7 @@ abstract public class LuaValue extends Varargs { * {@link LuaString} and be convertible to a number *

    * For metatag processing {@link #sub(LuaValue)} must be used - * + * * @param lhs The left-hand-side value from which to perform the subtraction * @return value of {@code (lhs - this)} if this is numeric * @throws LuaError if {@code this} is not a number or string convertible to @@ -2682,7 +2688,7 @@ abstract public class LuaValue extends Varargs { *

    * Each operand must derive from {@link LuaNumber} or derive from * {@link LuaString} and be convertible to a number - * + * * @param rhs The right-hand-side value to perform the multiply with * @return value of {@code (this * rhs)} if both are numeric, or * {@link LuaValue} if metatag processing occurs @@ -2699,7 +2705,7 @@ abstract public class LuaValue extends Varargs { *

    * {@code this} must derive from {@link LuaNumber} or derive from * {@link LuaString} and be convertible to a number - * + * * @param rhs The right-hand-side value to perform the multiply with * @return value of {@code (this * rhs)} if this is numeric * @throws LuaError if {@code this} is not a number or string convertible to @@ -2714,7 +2720,7 @@ abstract public class LuaValue extends Varargs { *

    * {@code this} must derive from {@link LuaNumber} or derive from * {@link LuaString} and be convertible to a number - * + * * @param rhs The right-hand-side value to perform the multiply with * @return value of {@code (this * rhs)} if this is numeric * @throws LuaError if {@code this} is not a number or string convertible to @@ -2728,7 +2734,7 @@ abstract public class LuaValue extends Varargs { *

    * Each operand must derive from {@link LuaNumber} or derive from * {@link LuaString} and be convertible to a number - * + * * @param rhs The power to raise this value to * @return value of {@code (this ^ rhs)} if both are numeric, or * {@link LuaValue} if metatag processing occurs @@ -2745,7 +2751,7 @@ abstract public class LuaValue extends Varargs { *

    * {@code this} must derive from {@link LuaNumber} or derive from * {@link LuaString} and be convertible to a number - * + * * @param rhs The power to raise this value to * @return value of {@code (this ^ rhs)} if this is numeric * @throws LuaError if {@code this} is not a number or string convertible to @@ -2760,7 +2766,7 @@ abstract public class LuaValue extends Varargs { *

    * {@code this} must derive from {@link LuaNumber} or derive from * {@link LuaString} and be convertible to a number - * + * * @param rhs The power to raise this value to * @return value of {@code (this ^ rhs)} if this is numeric * @throws LuaError if {@code this} is not a number or string convertible to @@ -2775,7 +2781,7 @@ abstract public class LuaValue extends Varargs { *

    * {@code this} must derive from {@link LuaNumber} or derive from * {@link LuaString} and be convertible to a number - * + * * @param lhs The left-hand-side value which will be raised to this power * @return value of {@code (lhs ^ this)} if this is numeric * @throws LuaError if {@code this} is not a number or string convertible to @@ -2792,7 +2798,7 @@ abstract public class LuaValue extends Varargs { *

    * {@code this} must derive from {@link LuaNumber} or derive from * {@link LuaString} and be convertible to a number - * + * * @param lhs The left-hand-side value which will be raised to this power * @return value of {@code (lhs ^ this)} if this is numeric * @throws LuaError if {@code this} is not a number or string convertible to @@ -2809,7 +2815,7 @@ abstract public class LuaValue extends Varargs { *

    * Each operand must derive from {@link LuaNumber} or derive from * {@link LuaString} and be convertible to a number - * + * * @param rhs The right-hand-side value to perform the divulo with * @return value of {@code (this / rhs)} if both are numeric, or * {@link LuaValue} if metatag processing occurs @@ -2828,7 +2834,7 @@ abstract public class LuaValue extends Varargs { * {@link LuaString} and be convertible to a number *

    * For metatag processing {@link #div(LuaValue)} must be used - * + * * @param rhs The right-hand-side value to perform the divulo with * @return value of {@code (this / rhs)} if this is numeric * @throws LuaError if {@code this} is not a number or string convertible to @@ -2845,7 +2851,7 @@ abstract public class LuaValue extends Varargs { * {@link LuaString} and be convertible to a number *

    * For metatag processing {@link #div(LuaValue)} must be used - * + * * @param rhs The right-hand-side value to perform the divulo with * @return value of {@code (this / rhs)} if this is numeric * @throws LuaError if {@code this} is not a number or string convertible to @@ -2860,7 +2866,7 @@ abstract public class LuaValue extends Varargs { *

    * {@code this} must derive from {@link LuaNumber} or derive from * {@link LuaString} and be convertible to a number - * + * * @param lhs The left-hand-side value which will be divided by this * @return value of {@code (lhs / this)} if this is numeric * @throws LuaError if {@code this} is not a number or string convertible to @@ -2877,7 +2883,7 @@ abstract public class LuaValue extends Varargs { *

    * Each operand must derive from {@link LuaNumber} or derive from * {@link LuaString} and be convertible to a number - * + * * @param rhs The right-hand-side value to perform the modulo with * @return value of {@code (this % rhs)} if both are numeric, or * {@link LuaValue} if metatag processing occurs @@ -2896,7 +2902,7 @@ abstract public class LuaValue extends Varargs { * {@link LuaString} and be convertible to a number *

    * For metatag processing {@link #mod(LuaValue)} must be used - * + * * @param rhs The right-hand-side value to perform the modulo with * @return value of {@code (this % rhs)} if this is numeric * @throws LuaError if {@code this} is not a number or string convertible to @@ -2913,7 +2919,7 @@ abstract public class LuaValue extends Varargs { * {@link LuaString} and be convertible to a number *

    * For metatag processing {@link #mod(LuaValue)} must be used - * + * * @param rhs The right-hand-side value to perform the modulo with * @return value of {@code (this % rhs)} if this is numeric * @throws LuaError if {@code this} is not a number or string convertible to @@ -2928,7 +2934,7 @@ abstract public class LuaValue extends Varargs { *

    * {@code this} must derive from {@link LuaNumber} or derive from * {@link LuaString} and be convertible to a number - * + * * @param lhs The left-hand-side value which will be modulo'ed by this * @return value of {@code (lhs % this)} if this is numeric * @throws LuaError if {@code this} is not a number or string convertible to @@ -2944,7 +2950,7 @@ abstract public class LuaValue extends Varargs { *

    * Finds the supplied metatag value for {@code this} or {@code op2} and * invokes it, or throws {@link LuaError} if neither is defined. - * + * * @param tag The metatag to look up * @param op2 The other operand value to perform the operation with * @return {@link LuaValue} resulting from metatag processing @@ -2978,7 +2984,7 @@ abstract public class LuaValue extends Varargs { *

    * Finds the supplied metatag value for {@code this} and invokes it, or * throws {@link LuaError} if neither is defined. - * + * * @param tag The metatag to look up * @param op1 The value of the left-hand-side to perform the operation with * @return {@link LuaValue} resulting from metatag processing @@ -3010,7 +3016,7 @@ abstract public class LuaValue extends Varargs { *

    * To be comparable, both operands must derive from {@link LuaString} or * both must derive from {@link LuaNumber}. - * + * * @param rhs The right-hand-side value to perform the comparison with * @return {@link #TRUE} if {@code (this < rhs)}, {@link #FALSE} if not, or * {@link LuaValue} if metatag processing occurs @@ -3026,7 +3032,7 @@ abstract public class LuaValue extends Varargs { * including metatag processing, and returning {@link LuaValue}. *

    * To be comparable, this must derive from {@link LuaNumber}. - * + * * @param rhs The right-hand-side value to perform the comparison with * @return {@link #TRUE} if {@code (this < rhs)}, {@link #FALSE} if not, or * {@link LuaValue} if metatag processing occurs @@ -3042,7 +3048,7 @@ abstract public class LuaValue extends Varargs { * including metatag processing, and returning {@link LuaValue}. *

    * To be comparable, this must derive from {@link LuaNumber}. - * + * * @param rhs The right-hand-side value to perform the comparison with * @return {@link #TRUE} if {@code (this < rhs)}, {@link #FALSE} if not, or * {@link LuaValue} if metatag processing occurs @@ -3059,7 +3065,7 @@ abstract public class LuaValue extends Varargs { *

    * To be comparable, both operands must derive from {@link LuaString} or * both must derive from {@link LuaNumber}. - * + * * @param rhs The right-hand-side value to perform the comparison with * @return true if {@code (this < rhs)}, false if not, and boolean * interpreation of result if metatag processing occurs. @@ -3075,7 +3081,7 @@ abstract public class LuaValue extends Varargs { * including metatag processing, and returning java boolean. *

    * To be comparable, this must derive from {@link LuaNumber}. - * + * * @param rhs The right-hand-side value to perform the comparison with * @return true if {@code (this < rhs)}, false if not, and boolean * interpreation of result if metatag processing occurs. @@ -3092,7 +3098,7 @@ abstract public class LuaValue extends Varargs { *

    * To be comparable, both operands must derive from {@link LuaString} or * both must derive from {@link LuaNumber}. - * + * * @param rhs The right-hand-side value to perform the comparison with * @return true if {@code (this < rhs)}, false if not, and boolean * interpreation of result if metatag processing occurs. @@ -3110,7 +3116,7 @@ abstract public class LuaValue extends Varargs { *

    * To be comparable, both operands must derive from {@link LuaString} or * both must derive from {@link LuaNumber}. - * + * * @param rhs The right-hand-side value to perform the comparison with * @return {@link #TRUE} if {@code (this <= rhs)}, {@link #FALSE} if not, or * {@link LuaValue} if metatag processing occurs @@ -3127,7 +3133,7 @@ abstract public class LuaValue extends Varargs { * {@link LuaValue}. *

    * To be comparable, this must derive from {@link LuaNumber}. - * + * * @param rhs The right-hand-side value to perform the comparison with * @return {@link #TRUE} if {@code (this <= rhs)}, {@link #FALSE} if not, or * {@link LuaValue} if metatag processing occurs @@ -3143,7 +3149,7 @@ abstract public class LuaValue extends Varargs { * type, including metatag processing, and returning {@link LuaValue}. *

    * To be comparable, this must derive from {@link LuaNumber}. - * + * * @param rhs The right-hand-side value to perform the comparison with * @return {@link #TRUE} if {@code (this <= rhs)}, {@link #FALSE} if not, or * {@link LuaValue} if metatag processing occurs @@ -3161,7 +3167,7 @@ abstract public class LuaValue extends Varargs { *

    * To be comparable, both operands must derive from {@link LuaString} or * both must derive from {@link LuaNumber}. - * + * * @param rhs The right-hand-side value to perform the comparison with * @return true if {@code (this <= rhs)}, false if not, and boolean * interpreation of result if metatag processing occurs. @@ -3177,7 +3183,7 @@ abstract public class LuaValue extends Varargs { * type, including metatag processing, and returning java boolean. *

    * To be comparable, this must derive from {@link LuaNumber}. - * + * * @param rhs The right-hand-side value to perform the comparison with * @return true if {@code (this <= rhs)}, false if not, and boolean * interpreation of result if metatag processing occurs. @@ -3193,7 +3199,7 @@ abstract public class LuaValue extends Varargs { * double type, including metatag processing, and returning java boolean. *

    * To be comparable, this must derive from {@link LuaNumber}. - * + * * @param rhs The right-hand-side value to perform the comparison with * @return true if {@code (this <= rhs)}, false if not, and boolean * interpreation of result if metatag processing occurs. @@ -3211,7 +3217,7 @@ abstract public class LuaValue extends Varargs { *

    * To be comparable, both operands must derive from {@link LuaString} or * both must derive from {@link LuaNumber}. - * + * * @param rhs The right-hand-side value to perform the comparison with * @return {@link #TRUE} if {@code (this > rhs)}, {@link #FALSE} if not, or * {@link LuaValue} if metatag processing occurs @@ -3227,7 +3233,7 @@ abstract public class LuaValue extends Varargs { * type, including metatag processing, and returning {@link LuaValue}. *

    * To be comparable, this must derive from {@link LuaNumber}. - * + * * @param rhs The right-hand-side value to perform the comparison with * @return {@link #TRUE} if {@code (this > rhs)}, {@link #FALSE} if not, or * {@link LuaValue} if metatag processing occurs @@ -3243,7 +3249,7 @@ abstract public class LuaValue extends Varargs { * including metatag processing, and returning {@link LuaValue}. *

    * To be comparable, this must derive from {@link LuaNumber}. - * + * * @param rhs The right-hand-side value to perform the comparison with * @return {@link #TRUE} if {@code (this > rhs)}, {@link #FALSE} if not, or * {@link LuaValue} if metatag processing occurs @@ -3260,7 +3266,7 @@ abstract public class LuaValue extends Varargs { *

    * To be comparable, both operands must derive from {@link LuaString} or * both must derive from {@link LuaNumber}. - * + * * @param rhs The right-hand-side value to perform the comparison with * @return true if {@code (this > rhs)}, false if not, and boolean * interpreation of result if metatag processing occurs. @@ -3276,7 +3282,7 @@ abstract public class LuaValue extends Varargs { * including metatag processing, and returning java boolean. *

    * To be comparable, this must derive from {@link LuaNumber}. - * + * * @param rhs The right-hand-side value to perform the comparison with * @return true if {@code (this > rhs)}, false if not, and boolean * interpreation of result if metatag processing occurs. @@ -3293,7 +3299,7 @@ abstract public class LuaValue extends Varargs { *

    * To be comparable, both operands must derive from {@link LuaString} or * both must derive from {@link LuaNumber}. - * + * * @param rhs The right-hand-side value to perform the comparison with * @return true if {@code (this > rhs)}, false if not, and boolean * interpreation of result if metatag processing occurs. @@ -3311,7 +3317,7 @@ abstract public class LuaValue extends Varargs { *

    * To be comparable, both operands must derive from {@link LuaString} or * both must derive from {@link LuaNumber}. - * + * * @param rhs The right-hand-side value to perform the comparison with * @return {@link #TRUE} if {@code (this >= rhs)}, {@link #FALSE} if not, or * {@link LuaValue} if metatag processing occurs @@ -3328,7 +3334,7 @@ abstract public class LuaValue extends Varargs { * {@link LuaValue}. *

    * To be comparable, this must derive from {@link LuaNumber}. - * + * * @param rhs The right-hand-side value to perform the comparison with * @return {@link #TRUE} if {@code (this >= rhs)}, {@link #FALSE} if not, or * {@link LuaValue} if metatag processing occurs @@ -3344,7 +3350,7 @@ abstract public class LuaValue extends Varargs { * int type, including metatag processing, and returning {@link LuaValue}. *

    * To be comparable, this must derive from {@link LuaNumber}. - * + * * @param rhs The right-hand-side value to perform the comparison with * @return {@link #TRUE} if {@code (this >= rhs)}, {@link #FALSE} if not, or * {@link LuaValue} if metatag processing occurs @@ -3362,7 +3368,7 @@ abstract public class LuaValue extends Varargs { *

    * To be comparable, both operands must derive from {@link LuaString} or * both must derive from {@link LuaNumber}. - * + * * @param rhs The right-hand-side value to perform the comparison with * @return true if {@code (this >= rhs)}, false if not, and boolean * interpreation of result if metatag processing occurs. @@ -3378,7 +3384,7 @@ abstract public class LuaValue extends Varargs { * int type, including metatag processing, and returning java boolean. *

    * To be comparable, this must derive from {@link LuaNumber}. - * + * * @param rhs The right-hand-side value to perform the comparison with * @return true if {@code (this >= rhs)}, false if not, and boolean * interpreation of result if metatag processing occurs. @@ -3394,7 +3400,7 @@ abstract public class LuaValue extends Varargs { * double type, including metatag processing, and returning java boolean. *

    * To be comparable, this must derive from {@link LuaNumber}. - * + * * @param rhs The right-hand-side value to perform the comparison with * @return true if {@code (this >= rhs)}, false if not, and boolean * interpreation of result if metatag processing occurs. @@ -3410,7 +3416,7 @@ abstract public class LuaValue extends Varargs { *

    * Finds the supplied metatag value and invokes it, or throws * {@link LuaError} if none applies. - * + * * @param tag The metatag to look up * @param op1 The operand with which to to perform the operation * @return {@link LuaValue} resulting from metatag processing @@ -3437,7 +3443,7 @@ abstract public class LuaValue extends Varargs { *

    * Only strings can be compared, meaning each operand must derive from * {@link LuaString}. - * + * * @param rhs The right-hand-side value to perform the comparison with * @return int < 0 for {@code (this < rhs)}, int > 0 for * {@code (this > rhs)}, or 0 when same string. @@ -3451,7 +3457,7 @@ abstract public class LuaValue extends Varargs { *

    * Only strings can be compared, meaning each operand must derive from * {@link LuaString}. - * + * * @param rhs The right-hand-side value to perform the comparison with * @return int < 0 for {@code (this < rhs)}, int > 0 for * {@code (this > rhs)}, or 0 when same string. @@ -3465,7 +3471,7 @@ abstract public class LuaValue extends Varargs { *

    * Only strings and numbers as represented can be concatenated, meaning each * operand must derive from {@link LuaString} or {@link LuaNumber}. - * + * * @param rhs The right-hand-side value to perform the operation with * @return {@link LuaValue} resulting from concatenation of * {@code (this .. rhs)} @@ -3481,7 +3487,7 @@ abstract public class LuaValue extends Varargs { *

    * Only strings and numbers as represented can be concatenated, meaning each * operand must derive from {@link LuaString} or {@link LuaNumber}. - * + * * @param lhs The left-hand-side value onto which this will be concatenated * @return {@link LuaValue} resulting from concatenation of * {@code (lhs .. this)} @@ -3498,7 +3504,7 @@ abstract public class LuaValue extends Varargs { *

    * Only strings and numbers as represented can be concatenated, meaning each * operand must derive from {@link LuaString} or {@link LuaNumber}. - * + * * @param lhs The left-hand-side value onto which this will be concatenated * @return {@link LuaValue} resulting from concatenation of * {@code (lhs .. this)} @@ -3515,7 +3521,7 @@ abstract public class LuaValue extends Varargs { *

    * Only strings and numbers as represented can be concatenated, meaning each * operand must derive from {@link LuaString} or {@link LuaNumber}. - * + * * @param lhs The left-hand-side value onto which this will be concatenated * @return {@link LuaValue} resulting from concatenation of * {@code (lhs .. this)} @@ -3528,7 +3534,7 @@ abstract public class LuaValue extends Varargs { /** * Convert the value to a {@link Buffer} for more efficient concatenation of * multiple strings. - * + * * @return Buffer instance containing the string or number */ public Buffer buffer() { return new Buffer(this); } @@ -3539,7 +3545,7 @@ abstract public class LuaValue extends Varargs { *

    * Only strings and numbers as represented can be concatenated, meaning each * operand must derive from {@link LuaString} or {@link LuaNumber}. - * + * * @param rhs The right-hand-side {@link Buffer} to perform the operation * with * @return LuaString resulting from concatenation of {@code (this .. rhs)} @@ -3553,7 +3559,7 @@ abstract public class LuaValue extends Varargs { *

    * Finds the {@link #CONCAT} metatag value and invokes it, or throws * {@link LuaError} if it doesn't exist. - * + * * @param rhs The right-hand-side value to perform the operation with * @return {@link LuaValue} resulting from metatag processing for * {@link #CONCAT} metatag. @@ -3570,7 +3576,7 @@ abstract public class LuaValue extends Varargs { * Perform boolean {@code and} with another operand, based on lua rules for * boolean evaluation. This returns either {@code this} or {@code rhs} * depending on the boolean value for {@code this}. - * + * * @param rhs The right-hand-side value to perform the operation with * @return {@code this} if {@code this.toboolean()} is false, {@code rhs} * otherwise. @@ -3581,7 +3587,7 @@ abstract public class LuaValue extends Varargs { * Perform boolean {@code or} with another operand, based on lua rules for * boolean evaluation. This returns either {@code this} or {@code rhs} * depending on the boolean value for {@code this}. - * + * * @param rhs The right-hand-side value to perform the operation with * @return {@code this} if {@code this.toboolean()} is true, {@code rhs} * otherwise. @@ -3592,7 +3598,7 @@ abstract public class LuaValue extends Varargs { * Perform end-condition test in for-loop processing. *

    * Used in lua-bytecode to Java-bytecode conversion. - * + * * @param limit the numerical limit to complete the for loop * @param step the numberical step size to use. * @return true if limit has not been reached, false otherwise. @@ -3602,7 +3608,7 @@ abstract public class LuaValue extends Varargs { /** * Convert this value to a string if it is a {@link LuaString} or * {@link LuaNumber}, or throw a {@link LuaError} if it is not - * + * * @return {@link LuaString} corresponding to the value if a string or * number * @throws LuaError if not a string or number @@ -3612,7 +3618,7 @@ abstract public class LuaValue extends Varargs { /** * Return this value as a strong reference, or null if it was weak and is no * longer referenced. - * + * * @return {@link LuaValue} referred to, or null if it was weak and is no * longer referenced. * @see WeakTable @@ -3621,15 +3627,15 @@ abstract public class LuaValue extends Varargs { /** * Convert java boolean to a {@link LuaValue}. - * + * * @param b boolean value to convert * @return {@link #TRUE} if not or {@link #FALSE} if false */ - public static LuaBoolean valueOf(boolean b) { return b? LuaValue.TRUE: FALSE; }; + public static LuaBoolean valueOf(boolean b) { return b? LuaValue.TRUE: FALSE; } /** * Convert java int to a {@link LuaValue}. - * + * * @param i int value to convert * @return {@link LuaInteger} instance, possibly pooled, whose value is i */ @@ -3638,15 +3644,15 @@ abstract public class LuaValue extends Varargs { /** * Convert java double to a {@link LuaValue}. This may return a * {@link LuaInteger} or {@link LuaDouble} depending on the value supplied. - * + * * @param d double value to convert * @return {@link LuaNumber} instance, possibly pooled, whose value is d */ - public static LuaNumber valueOf(double d) { return LuaDouble.valueOf(d); }; + public static LuaNumber valueOf(double d) { return LuaDouble.valueOf(d); } /** * Convert java string to a {@link LuaValue}. - * + * * @param s String value to convert * @return {@link LuaString} instance, possibly pooled, whose value is s */ @@ -3654,7 +3660,7 @@ abstract public class LuaValue extends Varargs { /** * Convert bytes in an array to a {@link LuaValue}. - * + * * @param bytes byte array to convert * @return {@link LuaString} instance, possibly pooled, whose bytes are * those in the supplied array @@ -3663,7 +3669,7 @@ abstract public class LuaValue extends Varargs { /** * Convert bytes in an array to a {@link LuaValue}. - * + * * @param bytes byte array to convert * @param off offset into the byte array, starting at 0 * @param len number of bytes to include in the {@link LuaString} @@ -3676,14 +3682,14 @@ abstract public class LuaValue extends Varargs { /** * Construct an empty {@link LuaTable}. - * + * * @return new {@link LuaTable} instance with no values and no metatable. */ public static LuaTable tableOf() { return new LuaTable(); } /** * Construct a {@link LuaTable} initialized with supplied array values. - * + * * @param varargs {@link Varargs} containing the values to use in * initialization * @param firstarg the index of the first argument to use from the varargs, @@ -3696,7 +3702,7 @@ abstract public class LuaValue extends Varargs { /** * Construct an empty {@link LuaTable} preallocated to hold array and hashed * elements - * + * * @param narray Number of array elements to preallocate * @param nhash Number of hash elements to preallocate * @return new {@link LuaTable} instance with no values and no metatable, @@ -3706,7 +3712,7 @@ abstract public class LuaValue extends Varargs { /** * Construct a {@link LuaTable} initialized with supplied array values. - * + * * @param unnamedValues array of {@link LuaValue} containing the values to * use in initialization * @return new {@link LuaTable} instance with sequential elements coming @@ -3716,7 +3722,7 @@ abstract public class LuaValue extends Varargs { /** * Construct a {@link LuaTable} initialized with supplied array values. - * + * * @param unnamedValues array of {@link LuaValue} containing the first * values to use in initialization * @param lastarg {@link Varargs} containing additional values to use @@ -3731,7 +3737,7 @@ abstract public class LuaValue extends Varargs { /** * Construct a {@link LuaTable} initialized with supplied named values. - * + * * @param namedValues array of {@link LuaValue} containing the keys and * values to use in initialization in order * {@code {key-a, value-a, key-b, value-b, ...} } @@ -3745,7 +3751,7 @@ abstract public class LuaValue extends Varargs { * sequential elements. The named values will be assigned first, and the * sequential elements will be assigned later, possibly overwriting named * values at the same slot if there are conflicts. - * + * * @param namedValues array of {@link LuaValue} containing the keys and * values to use in initialization in order * {@code {key-a, value-a, key-b, value-b, ...} } @@ -3766,7 +3772,7 @@ abstract public class LuaValue extends Varargs { * will be assigned first, and the sequential elements will be assigned * later, possibly overwriting named values at the same slot if there are * conflicts. - * + * * @param namedValues array of {@link LuaValue} containing the keys and * values to use in initialization in order * {@code {key-a, value-a, key-b, value-b, ...} } @@ -3786,7 +3792,7 @@ abstract public class LuaValue extends Varargs { /** * Construct a LuaUserdata for an object. - * + * * @param o The java instance to be wrapped as userdata * @return {@link LuaUserdata} value wrapping the java instance. */ @@ -3794,7 +3800,7 @@ abstract public class LuaValue extends Varargs { /** * Construct a LuaUserdata for an object with a user supplied metatable. - * + * * @param o The java instance to be wrapped as userdata * @param metatable The metatble to associate with the userdata instance. * @return {@link LuaUserdata} value wrapping the java instance. @@ -3807,7 +3813,7 @@ abstract public class LuaValue extends Varargs { /** * Return value for field reference including metatag processing, or * {@link LuaValue#NIL} if it doesn't exist. - * + * * @param t {@link LuaValue} on which field is being referenced, typically * a table or something with the metatag {@link LuaValue#INDEX} * defined @@ -3825,7 +3831,7 @@ abstract public class LuaValue extends Varargs { do { if (t.istable()) { LuaValue res = t.rawget(key); - if ((!res.isnil()) || (tm = t.metatag(INDEX)).isnil()) + if (!res.isnil() || (tm = t.metatag(INDEX)).isnil()) return res; } else if ((tm = t.metatag(INDEX)).isnil()) t.indexerror(key.tojstring()); @@ -3839,7 +3845,7 @@ abstract public class LuaValue extends Varargs { /** * Perform field assignment including metatag processing. - * + * * @param t {@link LuaValue} on which value is being set, typically a * table or something with the metatag * {@link LuaValue#NEWINDEX} defined @@ -3854,7 +3860,7 @@ abstract public class LuaValue extends Varargs { int loop = 0; do { if (t.istable()) { - if ((!t.rawget(key).isnil()) || (tm = t.metatag(NEWINDEX)).isnil()) { + if (!t.rawget(key).isnil() || (tm = t.metatag(NEWINDEX)).isnil()) { t.rawset(key, value); return true; } @@ -3873,7 +3879,7 @@ abstract public class LuaValue extends Varargs { /** * Get particular metatag, or return {@link LuaValue#NIL} if it doesn't * exist - * + * * @param tag Metatag name to look up, typically a string such as * {@link LuaValue#INDEX} or {@link LuaValue#NEWINDEX} * @return {@link LuaValue} for tag {@code reason}, or {@link LuaValue#NIL} @@ -3887,7 +3893,7 @@ abstract public class LuaValue extends Varargs { /** * Get particular metatag, or throw {@link LuaError} if it doesn't exist - * + * * @param tag Metatag name to look up, typically a string such as * {@link LuaValue#INDEX} or {@link LuaValue#NEWINDEX} * @param reason Description of error when tag lookup fails. @@ -3923,7 +3929,7 @@ abstract public class LuaValue extends Varargs { /** * Throw {@link LuaError} indicating index was attempted on illegal type - * + * * @throws LuaError when called. */ private void indexerror(String key) { @@ -3932,7 +3938,7 @@ abstract public class LuaValue extends Varargs { /** * Construct a {@link Varargs} around an array of {@link LuaValue}s. - * + * * @param v The array of {@link LuaValue}s * @return {@link Varargs} wrapping the supplied values. * @see LuaValue#varargsOf(LuaValue, Varargs) @@ -3953,7 +3959,7 @@ abstract public class LuaValue extends Varargs { /** * Construct a {@link Varargs} around an array of {@link LuaValue}s. - * + * * @param v The array of {@link LuaValue}s * @param r {@link Varargs} contain values to include at the end * @return {@link Varargs} wrapping the supplied values. @@ -3976,7 +3982,7 @@ abstract public class LuaValue extends Varargs { /** * Construct a {@link Varargs} around an array of {@link LuaValue}s. - * + * * @param v The array of {@link LuaValue}s * @param offset number of initial values to skip in the array * @param length number of values to include from the array @@ -3999,10 +4005,10 @@ abstract public class LuaValue extends Varargs { /** * Construct a {@link Varargs} around an array of {@link LuaValue}s. - * + * * Caller must ensure that array contents are not mutated after this call or * undefined behavior will result. - * + * * @param v The array of {@link LuaValue}s * @param offset number of initial values to skip in the array * @param length number of values to include from the array @@ -4030,7 +4036,7 @@ abstract public class LuaValue extends Varargs { *

    * This can be used to wrap exactly 2 values, or a list consisting of 1 * initial value followed by another variable list of remaining values. - * + * * @param v First {@link LuaValue} in the {@link Varargs} * @param r {@link LuaValue} supplying the 2rd value, or {@link Varargs}s * supplying all values beyond the first @@ -4050,7 +4056,7 @@ abstract public class LuaValue extends Varargs { *

    * This can be used to wrap exactly 3 values, or a list consisting of 2 * initial values followed by another variable list of remaining values. - * + * * @param v1 First {@link LuaValue} in the {@link Varargs} * @param v2 Second {@link LuaValue} in the {@link Varargs} * @param v3 {@link LuaValue} supplying the 3rd value, or {@link Varargs}s @@ -4074,7 +4080,7 @@ abstract public class LuaValue extends Varargs { *

    * This method is typically not used directly by client code. Instead use * one of the function invocation methods. - * + * * @param func {@link LuaValue} to be called as a tail call * @param args {@link Varargs} containing the arguments to the call * @return {@link TailcallVarargs} to be used in tailcall oprocessing. @@ -4094,7 +4100,7 @@ abstract public class LuaValue extends Varargs { *

    * This should not be called directly, instead use one of the call * invocation functions. - * + * * @param args the arguments to the call invocation. * @return Varargs the return values, possible a TailcallVarargs. * @see LuaValue#call() @@ -4110,7 +4116,7 @@ abstract public class LuaValue extends Varargs { * Hook for implementations such as LuaJC to load the environment of the * main chunk into the first upvalue location. If the function has no * upvalues or is not a main chunk, calling this will be no effect. - * + * * @param env The environment to load into the first upvalue, if there is * one. */ @@ -4121,22 +4127,28 @@ abstract public class LuaValue extends Varargs { *

    * This is an internal class not intended to be used directly. Instead use * the predefined constant {@link LuaValue#NONE} - * + * * @see LuaValue#NONE */ private static final class None extends LuaNil { static None _NONE = new None(); + @Override public LuaValue arg(int i) { return NIL; } + @Override public int narg() { return 0; } + @Override public LuaValue arg1() { return NIL; } + @Override public String tojstring() { return "none"; } + @Override public Varargs subargs(final int start) { return start > 0? this: argerror(1, "start must be > 0"); } + @Override void copyto(LuaValue[] dest, int offset, int length) { for (; length > 0; length--) dest[offset++] = NIL; @@ -4146,12 +4158,13 @@ abstract public class LuaValue extends Varargs { /** * Create a {@code Varargs} instance containing arguments starting at index * {@code start} - * + * * @param start the index from which to include arguments, where 1 is the * first argument. * @return Varargs containing argument { start, start+1, ... , narg-start-1 * } */ + @Override public Varargs subargs(final int start) { if (start == 1) return this; diff --git a/luaj-core/src/main/java/org/luaj/vm2/Metatable.java b/luaj-core/src/main/java/org/luaj/vm2/Metatable.java index 70f7418e..f57b3647 100644 --- a/luaj-core/src/main/java/org/luaj/vm2/Metatable.java +++ b/luaj-core/src/main/java/org/luaj/vm2/Metatable.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 @@ -29,23 +29,23 @@ import org.luaj.vm2.LuaTable.Slot; interface Metatable { /** Return whether or not this table's keys are weak. */ - public boolean useWeakKeys(); + boolean useWeakKeys(); /** Return whether or not this table's values are weak. */ - public boolean useWeakValues(); + boolean useWeakValues(); /** Return this metatable as a LuaValue. */ - public LuaValue toLuaValue(); + LuaValue toLuaValue(); /** Return an instance of Slot appropriate for the given key and value. */ - public Slot entry(LuaValue key, LuaValue value); + Slot entry(LuaValue key, LuaValue value); /** Returns the given value wrapped in a weak reference if appropriate. */ - public LuaValue wrap(LuaValue value); + LuaValue wrap(LuaValue value); /** * Returns the value at the given index in the array, or null if it is a * weak reference that has been dropped. */ - public LuaValue arrayget(LuaValue[] array, int index); + LuaValue arrayget(LuaValue[] array, int index); } diff --git a/luaj-core/src/main/java/org/luaj/vm2/NonTableMetatable.java b/luaj-core/src/main/java/org/luaj/vm2/NonTableMetatable.java index 4cf112a8..6fa72761 100644 --- a/luaj-core/src/main/java/org/luaj/vm2/NonTableMetatable.java +++ b/luaj-core/src/main/java/org/luaj/vm2/NonTableMetatable.java @@ -10,26 +10,32 @@ class NonTableMetatable implements Metatable { this.value = value; } + @Override public boolean useWeakKeys() { return false; } + @Override public boolean useWeakValues() { return false; } + @Override public LuaValue toLuaValue() { return value; } + @Override public Slot entry(LuaValue key, LuaValue value) { return LuaTable.defaultEntry(key, value); } + @Override public LuaValue wrap(LuaValue value) { return value; } + @Override public LuaValue arrayget(LuaValue[] array, int index) { return array[index]; } diff --git a/luaj-core/src/main/java/org/luaj/vm2/OrphanedThread.java b/luaj-core/src/main/java/org/luaj/vm2/OrphanedThread.java index a1ff7a50..24337a32 100644 --- a/luaj-core/src/main/java/org/luaj/vm2/OrphanedThread.java +++ b/luaj-core/src/main/java/org/luaj/vm2/OrphanedThread.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 diff --git a/luaj-core/src/main/java/org/luaj/vm2/Print.java b/luaj-core/src/main/java/org/luaj/vm2/Print.java index 585d5bbd..08ca99be 100644 --- a/luaj-core/src/main/java/org/luaj/vm2/Print.java +++ b/luaj-core/src/main/java/org/luaj/vm2/Print.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,7 +26,7 @@ import java.io.PrintStream; /** * Debug helper class to pretty-print lua bytecodes. - * + * * @see Prototype * @see LuaClosure */ @@ -114,7 +114,7 @@ public class Print extends Lua { /** * Print the code in a prototype - * + * * @param f the {@link Prototype} */ public static void printCode(Prototype f) { @@ -128,7 +128,7 @@ public class Print extends Lua { /** * Print an opcode in a prototype - * + * * @param f the {@link Prototype} * @param pc the program counter to look up and print * @return pc same as above or changed @@ -139,7 +139,7 @@ public class Print extends Lua { /** * Print an opcode in a prototype - * + * * @param ps the {@link PrintStream} to print to * @param f the {@link Prototype} * @param pc the program counter to look up and print @@ -168,15 +168,15 @@ public class Print extends Lua { case iABC: ps.print(a); if (getBMode(o) != OpArgN) - ps.print(" " + (ISK(b)? (-1-INDEXK(b)): b)); + ps.print(" " + (ISK(b)? -1-INDEXK(b): b)); if (getCMode(o) != OpArgN) - ps.print(" " + (ISK(c)? (-1-INDEXK(c)): c)); + ps.print(" " + (ISK(c)? -1-INDEXK(c): c)); break; case iABx: if (getBMode(o) == OpArgK) { ps.print(a + " " + (-1-bx)); } else { - ps.print(a + " " + (bx)); + ps.print(a + " " + bx); } break; case iAsBx: @@ -274,9 +274,9 @@ public class Print extends Lua { break; case OP_SETLIST: if (c == 0) - ps.print(" ; " + ((int) code[++pc]) + " (stored in the next OP)"); + ps.print(" ; " + code[++pc] + " (stored in the next OP)"); else - ps.print(" ; " + ((int) c)); + ps.print(" ; " + c); break; case OP_VARARG: ps.print(" ; is_vararg=" + f.is_vararg); @@ -300,7 +300,7 @@ public class Print extends Lua { s = "(bstring)"; else s = "(string)"; - String a = (f.linedefined == 0)? "main": "function"; + String a = f.linedefined == 0? "main": "function"; ps.print("\n%" + a + " <" + s + ":" + f.linedefined + "," + f.lastlinedefined + "> (" + f.code.length + " instructions, " + f.code.length*4 + " bytes at " + id(f) + ")\n"); ps.print(f.numparams + " param, " + f.maxstacksize + " slot, " + f.upvalues.length + " upvalue, "); @@ -336,7 +336,7 @@ public class Print extends Lua { /** * Pretty-prints contents of a Prototype. - * + * * @param prototype Prototype to print. */ public static void print(Prototype prototype) { @@ -345,7 +345,7 @@ public class Print extends Lua { /** * Pretty-prints contents of a Prototype in short or long form. - * + * * @param prototype Prototype to print. * @param full true to print all fields, false to print short form. */ @@ -384,7 +384,7 @@ public class Print extends Lua { /** * Print the state of a {@link LuaClosure} that is being executed - * + * * @param cl the {@link LuaClosure} * @param pc the program counter * @param stack the stack of {@link LuaValue} diff --git a/luaj-core/src/main/java/org/luaj/vm2/Prototype.java b/luaj-core/src/main/java/org/luaj/vm2/Prototype.java index c62f7760..087b18b5 100644 --- a/luaj-core/src/main/java/org/luaj/vm2/Prototype.java +++ b/luaj-core/src/main/java/org/luaj/vm2/Prototype.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 @@ -23,16 +23,16 @@ package org.luaj.vm2; /** * Prototype representing compiled lua code. - * + * *

    * This is both a straight translation of the corresponding C type, and the main * data structure for execution of compiled lua bytecode. - * + * *

    * Generally, the {@link Prototype} is not constructed directly is an * intermediate result as lua code is loaded using * {@link Globals#load(java.io.Reader, String)}: - * + * *

      * {
      * 	@code
    @@ -40,11 +40,11 @@ package org.luaj.vm2;
      * 	globals.load(new StringReader("print 'hello'"), "main.lua").call();
      * }
      * 
    - * + * *

    * To create a {@link Prototype} directly, a compiler such as * {@link org.luaj.vm2.compiler.LuaC} may be used: - * + * *

      * {
      * 	@code
    @@ -52,31 +52,31 @@ package org.luaj.vm2;
      * 	Prototype p = LuaC.instance.compile(is, "script");
      * }
      * 
    - * + * * To simplify loading, the * {@link Globals#compilePrototype(java.io.InputStream, String)} method may be * used: - * + * *
      * {
      * 	@code
      * 	Prototype p = globals.compileProtoytpe(is, "script");
      * }
      * 
    - * + * * It may also be loaded from a {@link java.io.Reader} via * {@link Globals#compilePrototype(java.io.Reader, String)}: - * + * *
      * {
      * 	@code
      * 	Prototype p = globals.compileProtoytpe(new StringReader(script), "script");
      * }
      * 
    - * + * * To un-dump a binary file known to be a binary lua file that has been dumped * to a string, the {@link Globals.Undumper} interface may be used: - * + * *
      * {
      * 	@code
    @@ -84,10 +84,10 @@ package org.luaj.vm2;
      * 	Prototype p = globals.undumper.undump(lua_binary_file, "foo.lua");
      * }
      * 
    - * + * * To execute the code represented by the {@link Prototype} it must be supplied * to the constructor of a {@link LuaClosure}: - * + * *
      * {
      * 	@code
    @@ -96,17 +96,17 @@ package org.luaj.vm2;
      * 	f.call();
      * }
      * 
    - * + * * To simplify the debugging of prototype values, the contents may be printed * using {@link Print#print}: - * + * *
      *  {@code
      * Print.print(p);
      * }
      * 
    *

    - * + * * @see LuaClosure * @see Globals * @see Globals#undumper @@ -145,13 +145,14 @@ public class Prototype { upvalues = new Upvaldesc[n_upvalues]; } + @Override public String toString() { return source + ":" + linedefined + "-" + lastlinedefined; } /** * Get the name of a local variable. - * + * * @param number the local variable number to look up * @param pc the program counter * @return the name, or null if not found diff --git a/luaj-core/src/main/java/org/luaj/vm2/TailcallVarargs.java b/luaj-core/src/main/java/org/luaj/vm2/TailcallVarargs.java index d3a9ec60..bdd9e914 100644 --- a/luaj-core/src/main/java/org/luaj/vm2/TailcallVarargs.java +++ b/luaj-core/src/main/java/org/luaj/vm2/TailcallVarargs.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 @@ -35,7 +35,7 @@ package org.luaj.vm2; *

    * Normally, users of luaj need not concern themselves with the details of this * mechanism, as it is built into the core execution framework. - * + * * @see Prototype * @see org.luaj.vm2.luajc.LuaJC */ @@ -55,8 +55,10 @@ public class TailcallVarargs extends Varargs { this.args = LuaValue.varargsOf(object, args); } + @Override public boolean isTailcall() { return true; } + @Override public Varargs eval() { while ( result == null ) { Varargs r = func.onInvoke(args); @@ -73,24 +75,28 @@ public class TailcallVarargs extends Varargs { return result; } + @Override public LuaValue arg(int i) { if (result == null) eval(); return result.arg(i); } + @Override public LuaValue arg1() { if (result == null) eval(); return result.arg1(); } + @Override public int narg() { if (result == null) eval(); return result.narg(); } + @Override public Varargs subargs(int start) { if (result == null) eval(); diff --git a/luaj-core/src/main/java/org/luaj/vm2/UpValue.java b/luaj-core/src/main/java/org/luaj/vm2/UpValue.java index 62a3ac4e..3e746974 100644 --- a/luaj-core/src/main/java/org/luaj/vm2/UpValue.java +++ b/luaj-core/src/main/java/org/luaj/vm2/UpValue.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 @@ -24,18 +24,18 @@ package org.luaj.vm2; /** * Upvalue used with Closure formulation *

    - * + * * @see LuaClosure * @see Prototype */ public final class UpValue { - LuaValue[] array; // initially the stack, becomes a holder + LuaValue[] array; // initially the stack, becomes a holder int index; /** * Create an upvalue relative to a stack - * + * * @param stack the stack * @param index the index on the stack for the upvalue */ @@ -44,13 +44,14 @@ public final class UpValue { this.index = index; } + @Override public String toString() { return index + "/" + array.length + " " + array[index]; } /** * Convert this upvalue to a Java String - * + * * @return the Java String for this upvalue. * @see LuaValue#tojstring() */ @@ -60,22 +61,22 @@ public final class UpValue { /** * Get the value of the upvalue - * + * * @return the {@link LuaValue} for this upvalue */ - public final LuaValue getValue() { return array[index]; } + public LuaValue getValue() { return array[index]; } /** * Set the value of the upvalue - * + * * @param value the {@link LuaValue} to set it to */ - public final void setValue(LuaValue value) { array[index] = value; } + public void setValue(LuaValue value) { array[index] = value; } /** * Close this upvalue so it is no longer on the stack */ - public final void close() { + public void close() { LuaValue[] old = array; array = new LuaValue[] { old[index] }; old[index] = null; diff --git a/luaj-core/src/main/java/org/luaj/vm2/Upvaldesc.java b/luaj-core/src/main/java/org/luaj/vm2/Upvaldesc.java index 041e8e33..26233892 100644 --- a/luaj-core/src/main/java/org/luaj/vm2/Upvaldesc.java +++ b/luaj-core/src/main/java/org/luaj/vm2/Upvaldesc.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 @@ -38,6 +38,7 @@ public class Upvaldesc { this.idx = (short) idx; } + @Override public String toString() { return idx+(instack? " instack ": " closed ")+String.valueOf(name); } diff --git a/luaj-core/src/main/java/org/luaj/vm2/Varargs.java b/luaj-core/src/main/java/org/luaj/vm2/Varargs.java index b5f6c05e..2d4b92cb 100644 --- a/luaj-core/src/main/java/org/luaj/vm2/Varargs.java +++ b/luaj-core/src/main/java/org/luaj/vm2/Varargs.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 @@ -38,7 +38,7 @@ package org.luaj.vm2; * a call such as {@code LuaValue.varargsOf(LuaValue,Varargs)} or by taking a * portion of the args using {@code Varargs.subargs(int start)} *

    - * + * * @see LuaValue#varargsOf(LuaValue[]) * @see LuaValue#varargsOf(LuaValue, Varargs) * @see LuaValue#varargsOf(LuaValue[], Varargs) @@ -51,7 +51,7 @@ public abstract class Varargs { /** * Get the n-th argument value (1-based). - * + * * @param i the index of the argument to get, 1 is the first argument * @return Value at position i, or LuaValue.NIL if there is none. * @see Varargs#arg1() @@ -61,14 +61,14 @@ public abstract class Varargs { /** * Get the number of arguments, or 0 if there are none. - * + * * @return number of arguments. */ abstract public int narg(); /** * Get the first argument in the list. - * + * * @return LuaValue which is first in the list, or LuaValue.NIL if there are * no values. * @see Varargs#arg(int) @@ -78,14 +78,14 @@ public abstract class Varargs { /** * Evaluate any pending tail call and return result. - * + * * @return the evaluated tail call result */ public Varargs eval() { return this; } /** * Return true if this is a TailcallVarargs - * + * * @return true if a tail call, false otherwise */ public boolean isTailcall() { return false; } @@ -96,7 +96,7 @@ public abstract class Varargs { /** * Gets the type of argument {@code i} - * + * * @param i the index of the argument to convert, 1 is the first argument * @return int value corresponding to one of the LuaValue integer type * values @@ -113,7 +113,7 @@ public abstract class Varargs { /** * Tests if argument i is nil. - * + * * @param i the index of the argument to test, 1 is the first argument * @return true if the argument is nil or does not exist, false otherwise * @see LuaValue#TNIL @@ -122,7 +122,7 @@ public abstract class Varargs { /** * Tests if argument i is a function. - * + * * @param i the index of the argument to test, 1 is the first argument * @return true if the argument exists and is a function or closure, false * otherwise @@ -134,7 +134,7 @@ public abstract class Varargs { * Tests if argument i is a number. Since anywhere a number is required, a * string can be used that is a number, this will return true for both * numbers and strings that can be interpreted as numbers. - * + * * @param i the index of the argument to test, 1 is the first argument * @return true if the argument exists and is a number or string that can be * interpreted as a number, false otherwise @@ -146,7 +146,7 @@ public abstract class Varargs { /** * Tests if argument i is a string. Since all lua numbers can be used where * strings are used, this will return true for both strings and numbers. - * + * * @param i the index of the argument to test, 1 is the first argument * @return true if the argument exists and is a string or number, false * otherwise @@ -157,7 +157,7 @@ public abstract class Varargs { /** * Tests if argument i is a table. - * + * * @param i the index of the argument to test, 1 is the first argument * @return true if the argument exists and is a lua table, false otherwise * @see LuaValue#TTABLE @@ -166,7 +166,7 @@ public abstract class Varargs { /** * Tests if argument i is a thread. - * + * * @param i the index of the argument to test, 1 is the first argument * @return true if the argument exists and is a lua thread, false otherwise * @see LuaValue#TTHREAD @@ -175,7 +175,7 @@ public abstract class Varargs { /** * Tests if argument i is a userdata. - * + * * @param i the index of the argument to test, 1 is the first argument * @return true if the argument exists and is a userdata, false otherwise * @see LuaValue#TUSERDATA @@ -184,7 +184,7 @@ public abstract class Varargs { /** * Tests if a value exists at argument i. - * + * * @param i the index of the argument to test, 1 is the first argument * @return true if the argument exists, false otherwise */ @@ -193,7 +193,7 @@ public abstract class Varargs { /** * Return argument i as a boolean value, {@code defval} if nil, or throw a * LuaError if any other type. - * + * * @param i the index of the argument to test, 1 is the first argument * @return true if argument i is boolean true, false if it is false, or * defval if not supplied or nil @@ -204,7 +204,7 @@ public abstract class Varargs { /** * Return argument i as a closure, {@code defval} if nil, or throw a * LuaError if any other type. - * + * * @param i the index of the argument to test, 1 is the first argument * @return LuaClosure if argument i is a closure, or defval if not supplied * or nil @@ -215,7 +215,7 @@ public abstract class Varargs { /** * Return argument i as a double, {@code defval} if nil, or throw a LuaError * if it cannot be converted to one. - * + * * @param i the index of the argument to test, 1 is the first argument * @return java double value if argument i is a number or string that * converts to a number, or defval if not supplied or nil @@ -226,7 +226,7 @@ public abstract class Varargs { /** * Return argument i as a function, {@code defval} if nil, or throw a * LuaError if an incompatible type. - * + * * @param i the index of the argument to test, 1 is the first argument * @return LuaValue that can be called if argument i is lua function or * closure, or defval if not supplied or nil @@ -237,7 +237,7 @@ public abstract class Varargs { /** * Return argument i as a java int value, discarding any fractional part, * {@code defval} if nil, or throw a LuaError if not a number. - * + * * @param i the index of the argument to test, 1 is the first argument * @return int value with fraction discarded and truncated if necessary if * argument i is number, or defval if not supplied or nil @@ -248,7 +248,7 @@ public abstract class Varargs { /** * Return argument i as a java int value, {@code defval} if nil, or throw a * LuaError if not a number or is not representable by a java int. - * + * * @param i the index of the argument to test, 1 is the first argument * @return LuaInteger value that fits in a java int without rounding, or * defval if not supplied or nil @@ -260,7 +260,7 @@ public abstract class Varargs { /** * Return argument i as a java long value, discarding any fractional part, * {@code defval} if nil, or throw a LuaError if not a number. - * + * * @param i the index of the argument to test, 1 is the first argument * @return long value with fraction discarded and truncated if necessary if * argument i is number, or defval if not supplied or nil @@ -271,7 +271,7 @@ public abstract class Varargs { /** * Return argument i as a LuaNumber, {@code defval} if nil, or throw a * LuaError if not a number or string that can be converted to a number. - * + * * @param i the index of the argument to test, 1 is the first argument, or * defval if not supplied or nil * @return LuaNumber if argument i is number or can be converted to a number @@ -282,7 +282,7 @@ public abstract class Varargs { /** * Return argument i as a java String if a string or number, {@code defval} * if nil, or throw a LuaError if any other type - * + * * @param i the index of the argument to test, 1 is the first argument * @return String value if argument i is a string or number, or defval if * not supplied or nil @@ -293,7 +293,7 @@ public abstract class Varargs { /** * Return argument i as a LuaString if a string or number, {@code defval} if * nil, or throw a LuaError if any other type - * + * * @param i the index of the argument to test, 1 is the first argument * @return LuaString value if argument i is a string or number, or defval if * not supplied or nil @@ -304,7 +304,7 @@ public abstract class Varargs { /** * Return argument i as a LuaTable if a lua table, {@code defval} if nil, or * throw a LuaError if any other type. - * + * * @param i the index of the argument to test, 1 is the first argument * @return LuaTable value if a table, or defval if not supplied or nil * @exception LuaError if the argument is not a lua table @@ -314,7 +314,7 @@ public abstract class Varargs { /** * Return argument i as a LuaThread if a lua thread, {@code defval} if nil, * or throw a LuaError if any other type. - * + * * @param i the index of the argument to test, 1 is the first argument * @return LuaThread value if a thread, or defval if not supplied or nil * @exception LuaError if the argument is not a lua thread @@ -324,7 +324,7 @@ public abstract class Varargs { /** * Return argument i as a java Object if a userdata, {@code defval} if nil, * or throw a LuaError if any other type. - * + * * @param i the index of the argument to test, 1 is the first argument * @return java Object value if argument i is a userdata, or defval if not * supplied or nil @@ -336,7 +336,7 @@ public abstract class Varargs { * Return argument i as a java Object if it is a userdata whose instance * Class c or a subclass, {@code defval} if nil, or throw a LuaError if any * other type. - * + * * @param i the index of the argument to test, 1 is the first argument * @param c the class to which the userdata instance must be assignable * @return java Object value if argument i is a userdata whose instance @@ -348,7 +348,7 @@ public abstract class Varargs { /** * Return argument i as a LuaValue if it exists, or {@code defval}. - * + * * @param i the index of the argument to test, 1 is the first argument * @return LuaValue value if the argument exists, defval if not * @exception LuaError if the argument does not exist. @@ -358,7 +358,7 @@ public abstract class Varargs { /** * Return argument i as a boolean value, or throw an error if any other * type. - * + * * @param i the index of the argument to test, 1 is the first argument * @return true if argument i is boolean true, false if it is false * @exception LuaError if the argument is not a lua boolean @@ -367,7 +367,7 @@ public abstract class Varargs { /** * Return argument i as a closure, or throw an error if any other type. - * + * * @param i the index of the argument to test, 1 is the first argument * @return LuaClosure if argument i is a closure. * @exception LuaError if the argument is not a lua closure @@ -377,7 +377,7 @@ public abstract class Varargs { /** * Return argument i as a double, or throw an error if it cannot be * converted to one. - * + * * @param i the index of the argument to test, 1 is the first argument * @return java double value if argument i is a number or string that * converts to a number @@ -388,7 +388,7 @@ public abstract class Varargs { /** * Return argument i as a function, or throw an error if an incompatible * type. - * + * * @param i the index of the argument to test, 1 is the first argument * @return LuaValue that can be called if argument i is lua function or * closure @@ -399,7 +399,7 @@ public abstract class Varargs { /** * Return argument i as a java int value, or throw an error if it cannot be * converted to one. - * + * * @param i the index of the argument to test, 1 is the first argument * @return int value if argument i is a number or string that converts to a * number @@ -411,7 +411,7 @@ public abstract class Varargs { /** * Return argument i as a java int value, or throw an error if not a number * or is not representable by a java int. - * + * * @param i the index of the argument to test, 1 is the first argument * @return LuaInteger value that fits in a java int without rounding * @exception LuaError if the argument cannot be represented by a java int @@ -422,7 +422,7 @@ public abstract class Varargs { /** * Return argument i as a java long value, or throw an error if it cannot be * converted to one. - * + * * @param i the index of the argument to test, 1 is the first argument * @return long value if argument i is a number or string that converts to a * number @@ -434,7 +434,7 @@ public abstract class Varargs { /** * Return argument i as a LuaNumber, or throw an error if not a number or * string that can be converted to a number. - * + * * @param i the index of the argument to test, 1 is the first argument * @return LuaNumber if argument i is number or can be converted to a number * @exception LuaError if the argument is not a number @@ -444,7 +444,7 @@ public abstract class Varargs { /** * Return argument i as a java String if a string or number, or throw an * error if any other type - * + * * @param i the index of the argument to test, 1 is the first argument * @return String value if argument i is a string or number * @exception LuaError if the argument is not a string or number @@ -454,7 +454,7 @@ public abstract class Varargs { /** * Return argument i as a LuaString if a string or number, or throw an error * if any other type - * + * * @param i the index of the argument to test, 1 is the first argument * @return LuaString value if argument i is a string or number * @exception LuaError if the argument is not a string or number @@ -464,7 +464,7 @@ public abstract class Varargs { /** * Return argument i as a LuaTable if a lua table, or throw an error if any * other type. - * + * * @param i the index of the argument to test, 1 is the first argument * @return LuaTable value if a table * @exception LuaError if the argument is not a lua table @@ -474,7 +474,7 @@ public abstract class Varargs { /** * Return argument i as a LuaThread if a lua thread, or throw an error if * any other type. - * + * * @param i the index of the argument to test, 1 is the first argument * @return LuaThread value if a thread * @exception LuaError if the argument is not a lua thread @@ -484,7 +484,7 @@ public abstract class Varargs { /** * Return argument i as a java Object if a userdata, or throw an error if * any other type. - * + * * @param i the index of the argument to test, 1 is the first argument * @return java Object value if argument i is a userdata * @exception LuaError if the argument is not a userdata @@ -494,7 +494,7 @@ public abstract class Varargs { /** * Return argument i as a java Object if it is a userdata whose instance * Class c or a subclass, or throw an error if any other type. - * + * * @param i the index of the argument to test, 1 is the first argument * @param c the class to which the userdata instance must be assignable * @return java Object value if argument i is a userdata whose instance @@ -506,7 +506,7 @@ public abstract class Varargs { /** * Return argument i as a LuaValue if it exists, or throw an error. - * + * * @param i the index of the argument to test, 1 is the first argument * @return LuaValue value if the argument exists * @exception LuaError if the argument does not exist. @@ -516,7 +516,7 @@ public abstract class Varargs { /** * Return argument i as a LuaValue if it is not nil, or throw an error if it * is nil. - * + * * @param i the index of the argument to test, 1 is the first argument * @return LuaValue value if the argument is not nil * @exception LuaError if the argument doesn't exist or evaluates to nil. @@ -528,7 +528,7 @@ public abstract class Varargs { * passes, or throw an error. Returns normally if the value of {@code test} * is {@code true}, otherwise throws and argument error with the supplied * message, {@code msg}. - * + * * @param test user supplied assertion to test against * @param i the index to report in any error message * @param msg the error message to use when the test fails @@ -541,7 +541,7 @@ public abstract class Varargs { /** * Return true if there is no argument or nil at argument i. - * + * * @param i the index of the argument to test, 1 is the first argument * @return true if argument i contains either no argument or nil */ @@ -552,7 +552,7 @@ public abstract class Varargs { /** * Convert argument {@code i} to java boolean based on lua rules for boolean * evaluation. - * + * * @param i the index of the argument to convert, 1 is the first argument * @return {@code false} if argument i is nil or false, otherwise * {@code true} @@ -562,7 +562,7 @@ public abstract class Varargs { /** * Return argument i as a java byte value, discarding any fractional part * and truncating, or 0 if not a number. - * + * * @param i the index of the argument to convert, 1 is the first argument * @return byte value with fraction discarded and truncated if necessary if * argument i is number, otherwise 0 @@ -572,7 +572,7 @@ public abstract class Varargs { /** * Return argument i as a java char value, discarding any fractional part * and truncating, or 0 if not a number. - * + * * @param i the index of the argument to convert, 1 is the first argument * @return char value with fraction discarded and truncated if necessary if * argument i is number, otherwise 0 @@ -581,7 +581,7 @@ public abstract class Varargs { /** * Return argument i as a java double value or 0 if not a number. - * + * * @param i the index of the argument to convert, 1 is the first argument * @return double value if argument i is number, otherwise 0 */ @@ -590,7 +590,7 @@ public abstract class Varargs { /** * Return argument i as a java float value, discarding excess fractional * part and truncating, or 0 if not a number. - * + * * @param i the index of the argument to convert, 1 is the first argument * @return float value with excess fraction discarded and truncated if * necessary if argument i is number, otherwise 0 @@ -600,7 +600,7 @@ public abstract class Varargs { /** * Return argument i as a java int value, discarding any fractional part and * truncating, or 0 if not a number. - * + * * @param i the index of the argument to convert, 1 is the first argument * @return int value with fraction discarded and truncated if necessary if * argument i is number, otherwise 0 @@ -610,7 +610,7 @@ public abstract class Varargs { /** * Return argument i as a java long value, discarding any fractional part * and truncating, or 0 if not a number. - * + * * @param i the index of the argument to convert, 1 is the first argument * @return long value with fraction discarded and truncated if necessary if * argument i is number, otherwise 0 @@ -619,7 +619,7 @@ public abstract class Varargs { /** * Return argument i as a java String based on the type of the argument. - * + * * @param i the index of the argument to convert, 1 is the first argument * @return String value representing the type */ @@ -628,7 +628,7 @@ public abstract class Varargs { /** * Return argument i as a java short value, discarding any fractional part * and truncating, or 0 if not a number. - * + * * @param i the index of the argument to convert, 1 is the first argument * @return short value with fraction discarded and truncated if necessary if * argument i is number, otherwise 0 @@ -637,7 +637,7 @@ public abstract class Varargs { /** * Return argument i as a java Object if a userdata, or null. - * + * * @param i the index of the argument to convert, 1 is the first argument * @return java Object value if argument i is a userdata, otherwise null */ @@ -646,7 +646,7 @@ public abstract class Varargs { /** * Return argument i as a java Object if it is a userdata whose instance * Class c or a subclass, or null. - * + * * @param i the index of the argument to convert, 1 is the first argument * @param c the class to which the userdata instance must be assignable * @return java Object value if argument i is a userdata whose instance @@ -656,7 +656,7 @@ public abstract class Varargs { /** * Convert the list of varargs values to a human readable java String. - * + * * @return String value in human readable form such as {1,2}. */ public String tojstring() { @@ -673,16 +673,17 @@ public abstract class Varargs { /** * Convert the value or values to a java String using Varargs.tojstring() - * + * * @return String value in human readable form. * @see Varargs#tojstring() */ + @Override public String toString() { return tojstring(); } /** * Create a {@code Varargs} instance containing arguments starting at index * {@code start} - * + * * @param start the index from which to include arguments, where 1 is the * first argument. * @return Varargs containing argument { start, start+1, ... , narg-start-1 @@ -692,7 +693,7 @@ public abstract class Varargs { /** * Implementation of Varargs for use in the Varargs.subargs() function. - * + * * @see Varargs#subargs(int) */ static class SubVarargs extends Varargs { @@ -706,19 +707,23 @@ public abstract class Varargs { this.end = end; } + @Override public LuaValue arg(int i) { i += start-1; return i >= start && i <= end? v.arg(i): LuaValue.NIL; } + @Override public LuaValue arg1() { return v.arg(start); } + @Override public int narg() { return end+1-start; } + @Override public Varargs subargs(final int start) { if (start == 1) return this; @@ -741,7 +746,7 @@ public abstract class Varargs { *

    * This is an internal class not intended to be used directly. Instead use * the corresponding static method on LuaValue. - * + * * @see LuaValue#varargsOf(LuaValue, Varargs) */ static final class PairVarargs extends Varargs { @@ -753,7 +758,7 @@ public abstract class Varargs { *

    * This is an internal class not intended to be used directly. Instead * use the corresponding static method on LuaValue. - * + * * @see LuaValue#varargsOf(LuaValue, Varargs) */ PairVarargs(LuaValue v1, Varargs v2) { @@ -761,18 +766,22 @@ public abstract class Varargs { this.v2 = v2; } + @Override public LuaValue arg(int i) { return i == 1? v1: v2.arg(i-1); } + @Override public int narg() { return 1+v2.narg(); } + @Override public LuaValue arg1() { return v1; } + @Override public Varargs subargs(final int start) { if (start == 1) return this; @@ -789,7 +798,7 @@ public abstract class Varargs { *

    * This is an internal class not intended to be used directly. Instead use * the corresponding static methods on LuaValue. - * + * * @see LuaValue#varargsOf(LuaValue[]) * @see LuaValue#varargsOf(LuaValue[], Varargs) */ @@ -802,7 +811,7 @@ public abstract class Varargs { *

    * This is an internal class not intended to be used directly. Instead * use the corresponding static methods on LuaValue. - * + * * @see LuaValue#varargsOf(LuaValue[]) * @see LuaValue#varargsOf(LuaValue[], Varargs) */ @@ -811,16 +820,20 @@ public abstract class Varargs { this.r = r; } + @Override public LuaValue arg(int i) { return i < 1? LuaValue.NIL: i <= v.length? v[i-1]: r.arg(i-v.length); } + @Override public int narg() { return v.length+r.narg(); } + @Override public LuaValue arg1() { return v.length > 0? v[0]: r.arg1(); } + @Override public Varargs subargs(int start) { if (start <= 0) LuaValue.argerror(1, "start must be > 0"); @@ -831,6 +844,7 @@ public abstract class Varargs { return LuaValue.varargsOf(v, start-1, v.length-(start-1), r); } + @Override void copyto(LuaValue[] dest, int offset, int length) { int n = Math.min(v.length, length); System.arraycopy(v, 0, dest, offset, n); @@ -843,7 +857,7 @@ public abstract class Varargs { *

    * This is an internal class not intended to be used directly. Instead use * the corresponding static methods on LuaValue. - * + * * @see LuaValue#varargsOf(LuaValue[], int, int) * @see LuaValue#varargsOf(LuaValue[], int, int, Varargs) */ @@ -858,7 +872,7 @@ public abstract class Varargs { *

    * This is an internal class not intended to be used directly. Instead * use the corresponding static methods on LuaValue. - * + * * @see LuaValue#varargsOf(LuaValue[], int, int) */ ArrayPartVarargs(LuaValue[] v, int offset, int length) { @@ -874,7 +888,7 @@ public abstract class Varargs { *

    * This is an internal class not intended to be used directly. Instead * use the corresponding static method on LuaValue. - * + * * @see LuaValue#varargsOf(LuaValue[], int, int, Varargs) */ public ArrayPartVarargs(LuaValue[] v, int offset, int length, Varargs more) { @@ -884,18 +898,22 @@ public abstract class Varargs { this.more = more; } + @Override public LuaValue arg(final int i) { return i < 1? LuaValue.NIL: i <= length? v[offset+i-1]: more.arg(i-length); } + @Override public int narg() { return length+more.narg(); } + @Override public LuaValue arg1() { return length > 0? v[offset]: more.arg1(); } + @Override public Varargs subargs(int start) { if (start <= 0) LuaValue.argerror(1, "start must be > 0"); @@ -906,6 +924,7 @@ public abstract class Varargs { return LuaValue.varargsOf(v, offset+start-1, length-(start-1), more); } + @Override void copyto(LuaValue[] dest, int offset, int length) { int n = Math.min(this.length, length); System.arraycopy(this.v, this.offset, dest, offset, n); @@ -916,7 +935,7 @@ public abstract class Varargs { /** * Copy values in a varargs into a destination array. Internal utility * method not intended to be called directly from user code. - * + * * @return Varargs containing same values, but flattened. */ void copyto(LuaValue[] dest, int offset, int length) { @@ -928,7 +947,7 @@ public abstract class Varargs { * Return Varargs that cannot be using a shared array for the storage, and * is flattened. Internal utility method not intended to be called directly * from user code. - * + * * @return Varargs containing same values, but flattened and with a new * array if needed. * @exclude diff --git a/luaj-core/src/main/java/org/luaj/vm2/WeakTable.java b/luaj-core/src/main/java/org/luaj/vm2/WeakTable.java index 468d8882..f360f516 100644 --- a/luaj-core/src/main/java/org/luaj/vm2/WeakTable.java +++ b/luaj-core/src/main/java/org/luaj/vm2/WeakTable.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 @@ -37,8 +37,8 @@ import org.luaj.vm2.LuaTable.StrongSlot; */ public class WeakTable implements Metatable { - private boolean weakkeys, weakvalues; - private LuaValue backing; + private final boolean weakkeys, weakvalues; + private final LuaValue backing; public static LuaTable make(boolean weakkeys, boolean weakvalues) { LuaString mode; @@ -49,17 +49,17 @@ public class WeakTable implements Metatable { } else if (weakvalues) { mode = LuaString.valueOf("v"); } else { - return LuaTable.tableOf(); + return LuaValue.tableOf(); } - LuaTable table = LuaTable.tableOf(); - LuaTable mt = LuaTable.tableOf(new LuaValue[] { LuaValue.MODE, mode }); + LuaTable table = LuaValue.tableOf(); + LuaTable mt = LuaValue.tableOf(new LuaValue[] { LuaValue.MODE, mode }); table.setmetatable(mt); return table; } /** * Construct a table with weak keys, weak values, or both - * + * * @param weakkeys true to let the table have weak keys * @param weakvalues true to let the table have weak values */ @@ -69,18 +69,22 @@ public class WeakTable implements Metatable { this.backing = backing; } + @Override public boolean useWeakKeys() { return weakkeys; } + @Override public boolean useWeakValues() { return weakvalues; } + @Override public LuaValue toLuaValue() { return backing; } + @Override public Slot entry(LuaValue key, LuaValue value) { value = value.strongvalue(); if (value == null) @@ -110,10 +114,12 @@ public class WeakTable implements Metatable { this.next = next; } + @Override public abstract int keyindex(int hashMask); public abstract Slot set(LuaValue value); + @Override public StrongSlot first() { LuaValue key = strongkey(); LuaValue value = strongvalue(); @@ -126,25 +132,30 @@ public class WeakTable implements Metatable { } } + @Override public StrongSlot find(LuaValue key) { StrongSlot first = first(); - return (first != null)? first.find(key): null; + return first != null? first.find(key): null; } + @Override public boolean keyeq(LuaValue key) { StrongSlot first = first(); - return (first != null) && first.keyeq(key); + return first != null && first.keyeq(key); } + @Override public Slot rest() { return next; } + @Override public int arraykey(int max) { // Integer keys can never be weak. return 0; } + @Override public Slot set(StrongSlot target, LuaValue value) { LuaValue key = strongkey(); if (key != null && target.find(key) != null) { @@ -159,8 +170,9 @@ public class WeakTable implements Metatable { } } + @Override public Slot add(Slot entry) { - next = (next != null)? next.add(entry): entry; + next = next != null? next.add(entry): entry; if (strongkey() != null && strongvalue() != null) { return this; } else { @@ -168,6 +180,7 @@ public class WeakTable implements Metatable { } } + @Override public Slot remove(StrongSlot target) { LuaValue key = strongkey(); if (key == null) { @@ -181,6 +194,7 @@ public class WeakTable implements Metatable { } } + @Override public Slot relink(Slot rest) { if (strongkey() != null && strongvalue() != null) { if (rest == null && this.next == null) { @@ -218,19 +232,23 @@ public class WeakTable implements Metatable { this.keyhash = copyFrom.keyhash; } + @Override public int keyindex(int mask) { return LuaTable.hashmod(keyhash, mask); } + @Override public Slot set(LuaValue value) { this.value = value; return this; } + @Override public LuaValue strongkey() { return strengthen(key); } + @Override protected WeakSlot copy(Slot rest) { return new WeakKeySlot(this, rest); } @@ -246,19 +264,23 @@ public class WeakTable implements Metatable { super(copyFrom.key, copyFrom.value, next); } + @Override public int keyindex(int mask) { return LuaTable.hashSlot(strongkey(), mask); } + @Override public Slot set(LuaValue value) { this.value = weaken(value); return this; } + @Override public LuaValue strongvalue() { return strengthen(value); } + @Override protected WeakSlot copy(Slot next) { return new WeakValueSlot(this, next); } @@ -278,23 +300,28 @@ public class WeakTable implements Metatable { keyhash = copyFrom.keyhash; } + @Override public int keyindex(int hashMask) { return LuaTable.hashmod(keyhash, hashMask); } + @Override public Slot set(LuaValue value) { this.value = weaken(value); return this; } + @Override public LuaValue strongkey() { return strengthen(key); } + @Override public LuaValue strongvalue() { return strengthen(value); } + @Override protected WeakSlot copy(Slot next) { return new WeakKeyAndValueSlot(this, next); } @@ -302,7 +329,7 @@ public class WeakTable implements Metatable { /** * Self-sent message to convert a value to its weak counterpart - * + * * @param value value to convert * @return {@link LuaValue} that is a strong or weak reference, depending on * type of {@code value} @@ -322,7 +349,7 @@ public class WeakTable implements Metatable { /** * Unwrap a LuaValue from a WeakReference and/or WeakUserdata. - * + * * @param ref reference to convert * @return LuaValue or null * @see #weaken(LuaValue) @@ -339,7 +366,7 @@ public class WeakTable implements Metatable { /** * Internal class to implement weak values. - * + * * @see WeakTable */ static class WeakValue extends LuaValue { @@ -349,25 +376,30 @@ public class WeakTable implements Metatable { ref = new WeakReference(value); } + @Override public int type() { illegal("type", "weak value"); return 0; } + @Override public String typename() { illegal("typename", "weak value"); return null; } + @Override public String toString() { return "weak<" + ref.get() + ">"; } + @Override public LuaValue strongvalue() { Object o = ref.get(); return (LuaValue) o; } + @Override public boolean raweq(LuaValue rhs) { Object o = ref.get(); return o != null && rhs.raweq((LuaValue) o); @@ -376,7 +408,7 @@ public class WeakTable implements Metatable { /** * Internal class to implement weak userdata values. - * + * * @see WeakTable */ static final class WeakUserdata extends WeakValue { @@ -389,6 +421,7 @@ public class WeakTable implements Metatable { mt = value.getmetatable(); } + @Override public LuaValue strongvalue() { Object u = ref.get(); if (u != null) @@ -404,10 +437,12 @@ public class WeakTable implements Metatable { } } + @Override public LuaValue wrap(LuaValue value) { return weakvalues? weaken(value): value; } + @Override public LuaValue arrayget(LuaValue[] array, int index) { LuaValue value = array[index]; if (value != null) { diff --git a/luaj-core/src/main/java/org/luaj/vm2/compiler/Constants.java b/luaj-core/src/main/java/org/luaj/vm2/compiler/Constants.java index 60a7fcd6..143d952d 100644 --- a/luaj-core/src/main/java/org/luaj/vm2/compiler/Constants.java +++ b/luaj-core/src/main/java/org/luaj/vm2/compiler/Constants.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 @@ -31,7 +31,7 @@ import org.luaj.vm2.Upvaldesc; /** * Constants used by the LuaC compiler and related classes. - * + * * @see LuaC * @see FuncState */ @@ -59,27 +59,27 @@ public class Constants extends Lua { } static void SET_OPCODE(InstructionPtr i, int o) { - i.set((i.get() & (MASK_NOT_OP)) | ((o< * A lua binary file is created via {@link DumpState#dump}: - * + * *

      * {
      * 	@code
    @@ -51,9 +51,9 @@ import org.luaj.vm2.Prototype;
      * 	byte[] lua_binary_file_bytes = o.toByteArray();
      * }
      * 
    - * + * * The {@link LoadState} may be used directly to undump these bytes: - * + * *
      *  {@code
      * Prototypep = LoadState.instance.undump(new ByteArrayInputStream(lua_binary_file_bytes), "main.lua");
    @@ -61,10 +61,10 @@ import org.luaj.vm2.Prototype;
      * c.call();
      * }
      * 
    - * - * + * + * * More commonly, the {@link Globals#undumper} may be used to undump them: - * + * *
      * {
      * 	@code
    @@ -73,7 +73,7 @@ import org.luaj.vm2.Prototype;
      * 	c.call();
      * }
      * 
    - * + * * @see luac * @see LoadState * @see Globals @@ -131,9 +131,9 @@ public class DumpState { void dumpInt(int x) throws IOException { if (IS_LITTLE_ENDIAN) { writer.writeByte(x & 0xff); - writer.writeByte((x>>8) & 0xff); - writer.writeByte((x>>16) & 0xff); - writer.writeByte((x>>24) & 0xff); + writer.writeByte(x>>8 & 0xff); + writer.writeByte(x>>16 & 0xff); + writer.writeByte(x>>24 & 0xff); } else { writer.writeInt(x); } @@ -286,7 +286,7 @@ public class DumpState { } /** - * + * * @param f the function to dump * @param w the output stream to dump to * @param stripDebug true to strip debugging info, false otherwise @@ -312,7 +312,7 @@ public class DumpState { DumpState D = new DumpState(w, stripDebug); D.IS_LITTLE_ENDIAN = littleendian; D.NUMBER_FORMAT = numberFormat; - D.SIZEOF_LUA_NUMBER = (numberFormat == NUMBER_FORMAT_INTS_ONLY? 4: 8); + D.SIZEOF_LUA_NUMBER = numberFormat == NUMBER_FORMAT_INTS_ONLY? 4: 8; D.dumpHeader(); D.dumpFunction(f); return D.status; diff --git a/luaj-core/src/main/java/org/luaj/vm2/compiler/FuncState.java b/luaj-core/src/main/java/org/luaj/vm2/compiler/FuncState.java index 40902616..25306d91 100644 --- a/luaj-core/src/main/java/org/luaj/vm2/compiler/FuncState.java +++ b/luaj-core/src/main/java/org/luaj/vm2/compiler/FuncState.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 @@ -43,7 +43,7 @@ public class FuncState extends Constants { short nactvar; /* # active locals outside the breakable structure */ boolean upval; /* true if some variable in the block is an upvalue */ boolean isloop; /* true if `block' is a loop */ - }; + } Prototype f; /* current function header */ Hashtable h; /* table to find (and reuse) elements in `k' */ @@ -106,7 +106,7 @@ public class FuncState extends Constants { void errorlimit(int limit, String what) { // TODO: report message logic. - String msg = (f.linedefined == 0)? ls.L.pushfstring("main function has more than " + limit + " " + what) + String msg = f.linedefined == 0? ls.L.pushfstring("main function has more than " + limit + " " + what) : ls.L.pushfstring("function at line " + f.linedefined + " has more than " + limit + " " + what); ls.lexerror(msg, 0); } @@ -118,7 +118,7 @@ public class FuncState extends Constants { } void removevars(int tolevel) { - ls.dyd.n_actvar -= (nactvar-tolevel); + ls.dyd.n_actvar -= nactvar-tolevel; while ( nactvar > tolevel ) getlocvar(--nactvar).endpc = pc; } @@ -245,7 +245,7 @@ public class FuncState extends Constants { } boolean hasmultret(int k) { - return ((k) == LexState.VCALL || (k) == LexState.VVARARG); + return k == LexState.VCALL || k == LexState.VVARARG; } void lastlistfield(ConsControl cc) { @@ -276,7 +276,7 @@ public class FuncState extends Constants { if (GET_OPCODE(previous_code) == OP_LOADNIL) { int pfrom = GETARG_A(previous_code); int pl = pfrom+GETARG_B(previous_code); - if ((pfrom <= from && from <= pl+1) || (from <= pfrom && pfrom <= l+1)) { /* can connect both? */ + if (pfrom <= from && from <= pl+1 || from <= pfrom && pfrom <= l+1) { /* can connect both? */ if (pfrom < from) from = pfrom; /* from = min(from, pfrom) */ if (pl > l) @@ -334,7 +334,7 @@ public class FuncState extends Constants { return LexState.NO_JUMP; else /* turn offset into absolute position */ - return (pc+1)+offset; + return pc+1+offset; } InstructionPtr getjumpcontrol(int pc) { @@ -466,7 +466,7 @@ public class FuncState extends Constants { return ((Integer) h.get(v)).intValue(); } final int idx = this.nk; - this.h.put(v, new Integer(idx)); + this.h.put(v, Integer.valueOf(idx)); final Prototype f = this.f; if (f.k == null || nk+1 >= f.k.length) f.k = realloc(f.k, nk*2+1); @@ -482,14 +482,14 @@ public class FuncState extends Constants { if (r instanceof LuaDouble) { double d = r.todouble(); int i = (int) d; - if (d == (double) i) + if (d == i) r = LuaInteger.valueOf(i); } return this.addk(r); } int boolK(boolean b) { - return this.addk((b? LuaValue.TRUE: LuaValue.FALSE)); + return this.addk(b? LuaValue.TRUE: LuaValue.FALSE); } int nilK() { @@ -562,7 +562,7 @@ public class FuncState extends Constants { } case LexState.VFALSE: case LexState.VTRUE: { - this.codeABC(OP_LOADBOOL, reg, (e.k == LexState.VTRUE? 1: 0), 0); + this.codeABC(OP_LOADBOOL, reg, e.k == LexState.VTRUE? 1: 0, 0); break; } case LexState.VK: { @@ -608,7 +608,7 @@ public class FuncState extends Constants { int p_f = LexState.NO_JUMP; /* position of an eventual LOAD false */ int p_t = LexState.NO_JUMP; /* position of an eventual LOAD true */ if (this.need_value(e.t.i) || this.need_value(e.f.i)) { - int fj = (e.k == LexState.VJMP)? LexState.NO_JUMP: this.jump(); + int fj = e.k == LexState.VJMP? LexState.NO_JUMP: this.jump(); p_f = this.code_label(reg, 0, 1); p_t = this.code_label(reg, 1, 0); this.patchtohere(fj); @@ -662,7 +662,7 @@ public class FuncState extends Constants { case LexState.VFALSE: case LexState.VNIL: { if (this.nk <= MAXINDEXRK) { /* constant fit in RK operand? */ - e.u.info = (e.k == LexState.VNIL)? this.nilK(): this.boolK((e.k == LexState.VTRUE)); + e.u.info = e.k == LexState.VNIL? this.nilK(): this.boolK(e.k == LexState.VTRUE); e.k = LexState.VK; return RKASK(e.u.info); } else @@ -699,7 +699,7 @@ public class FuncState extends Constants { break; } case LexState.VINDEXED: { - int op = (var.u.ind_vt == LexState.VLOCAL)? OP_SETTABLE: OP_SETTABUP; + int op = var.u.ind_vt == LexState.VLOCAL? OP_SETTABLE: OP_SETTABUP; int e = this.exp2RK(ex); this.codeABC(op, var.u.ind_t, var.u.ind_idx, e); break; @@ -730,7 +730,7 @@ public class FuncState extends Constants { && Lua.GET_OPCODE(pc.get()) != OP_TEST); // SETARG_A(pc, !(GETARG_A(pc.get()))); int a = GETARG_A(pc.get()); - int nota = (a != 0? 0: 1); + int nota = a != 0? 0: 1; SETARG_A(pc, nota); } @@ -739,7 +739,7 @@ public class FuncState extends Constants { int ie = this.getcode(e); if (GET_OPCODE(ie) == OP_NOT) { this.pc--; /* remove previous OP_NOT */ - return this.condjump(OP_TEST, GETARG_B(ie), 0, (cond != 0? 0: 1)); + return this.condjump(OP_TEST, GETARG_B(ie), 0, cond != 0? 0: 1); } /* else go through */ } @@ -838,14 +838,14 @@ public class FuncState extends Constants { } static boolean vkisinreg(int k) { - return ((k) == LexState.VNONRELOC || (k) == LexState.VLOCAL); + return k == LexState.VNONRELOC || k == LexState.VLOCAL; } void indexed(expdesc t, expdesc k) { t.u.ind_t = (short) t.u.info; t.u.ind_idx = (short) this.exp2RK(k); - LuaC._assert(t.k == LexState.VUPVAL || vkisinreg(t.k)); - t.u.ind_vt = (short) ((t.k == LexState.VUPVAL)? LexState.VUPVAL: LexState.VLOCAL); + Constants._assert(t.k == LexState.VUPVAL || vkisinreg(t.k)); + t.u.ind_vt = (short) (t.k == LexState.VUPVAL? LexState.VUPVAL: LexState.VLOCAL); t.k = LexState.VINDEXED; } @@ -895,10 +895,9 @@ public class FuncState extends Constants { } void codearith(int op, expdesc e1, expdesc e2, int line) { - if (constfolding(op, e1, e2)) - return; - else { - int o2 = (op != OP_UNM && op != OP_LEN)? this.exp2RK(e2): 0; + if (constfolding(op, e1, e2)) { + } else { + int o2 = op != OP_UNM && op != OP_LEN? this.exp2RK(e2): 0; int o1 = this.exp2RK(e1); if (o1 > o2) { this.freeexp(e1); @@ -1068,11 +1067,11 @@ public class FuncState extends Constants { this.dischargejpc(); /* `pc' will change */ /* put new instruction in code array */ if (f.code == null || this.pc+1 > f.code.length) - f.code = LuaC.realloc(f.code, this.pc*2+1); + f.code = Constants.realloc(f.code, this.pc*2+1); f.code[this.pc] = instruction; /* save corresponding line information */ if (f.lineinfo == null || this.pc+1 > f.lineinfo.length) - f.lineinfo = LuaC.realloc(f.lineinfo, this.pc*2+1); + f.lineinfo = Constants.realloc(f.lineinfo, this.pc*2+1); f.lineinfo[this.pc] = line; return this.pc++; } @@ -1108,7 +1107,7 @@ public class FuncState extends Constants { void setlist(int base, int nelems, int tostore) { int c = (nelems-1)/LFIELDS_PER_FLUSH+1; - int b = (tostore == LUA_MULTRET)? 0: tostore; + int b = tostore == LUA_MULTRET? 0: tostore; _assert(tostore != 0); if (c <= MAXARG_C) this.codeABC(OP_SETLIST, base, b, c); diff --git a/luaj-core/src/main/java/org/luaj/vm2/compiler/InstructionPtr.java b/luaj-core/src/main/java/org/luaj/vm2/compiler/InstructionPtr.java index 1325b194..6536737c 100644 --- a/luaj-core/src/main/java/org/luaj/vm2/compiler/InstructionPtr.java +++ b/luaj-core/src/main/java/org/luaj/vm2/compiler/InstructionPtr.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 diff --git a/luaj-core/src/main/java/org/luaj/vm2/compiler/IntPtr.java b/luaj-core/src/main/java/org/luaj/vm2/compiler/IntPtr.java index a54fd083..3e9fd16d 100644 --- a/luaj-core/src/main/java/org/luaj/vm2/compiler/IntPtr.java +++ b/luaj-core/src/main/java/org/luaj/vm2/compiler/IntPtr.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 diff --git a/luaj-core/src/main/java/org/luaj/vm2/compiler/LexState.java b/luaj-core/src/main/java/org/luaj/vm2/compiler/LexState.java index 65849e99..d4f73879 100644 --- a/luaj-core/src/main/java/org/luaj/vm2/compiler/LexState.java +++ b/luaj-core/src/main/java/org/luaj/vm2/compiler/LexState.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 @@ -45,16 +45,16 @@ public class LexState extends Constants { protected static final String RESERVED_LOCAL_VAR_FOR_INDEX = "(for index)"; // keywords array - protected static final String[] RESERVED_LOCAL_VAR_KEYWORDS = new String[] { RESERVED_LOCAL_VAR_FOR_CONTROL, + protected static final String[] RESERVED_LOCAL_VAR_KEYWORDS = { RESERVED_LOCAL_VAR_FOR_CONTROL, RESERVED_LOCAL_VAR_FOR_GENERATOR, RESERVED_LOCAL_VAR_FOR_INDEX, RESERVED_LOCAL_VAR_FOR_LIMIT, RESERVED_LOCAL_VAR_FOR_STATE, RESERVED_LOCAL_VAR_FOR_STEP }; private static final Hashtable RESERVED_LOCAL_VAR_KEYWORDS_TABLE = new Hashtable(); static { - for (int i = 0; i < RESERVED_LOCAL_VAR_KEYWORDS.length; i++) - RESERVED_LOCAL_VAR_KEYWORDS_TABLE.put(RESERVED_LOCAL_VAR_KEYWORDS[i], Boolean.TRUE); + for (String element : RESERVED_LOCAL_VAR_KEYWORDS) + RESERVED_LOCAL_VAR_KEYWORDS_TABLE.put(element, Boolean.TRUE); } - private static final int EOZ = (-1); + private static final int EOZ = -1; private static final int MAX_INT = Integer.MAX_VALUE-2; private static final int UCHAR_MAX = 255; // TODO, convert to unicode CHAR_MAX? private static final int LUAI_MAXCCALLS = 200; @@ -74,7 +74,7 @@ public class LexState extends Constants { ** Marks the end of a patch list. It is an invalid value both as an absolute ** address, and as a list link (would link an element to itself). */ - static final int NO_JUMP = (-1); + static final int NO_JUMP = -1; /* ** grep "ORDER OPR" if you change these enums @@ -102,7 +102,7 @@ public class LexState extends Constants { private static class SemInfo { LuaValue r; LuaString ts; - }; + } private static class Token { int token; @@ -113,7 +113,7 @@ public class LexState extends Constants { this.seminfo.r = other.seminfo.r; this.seminfo.ts = other.seminfo.ts; } - }; + } int current; /* current character (charint) */ int linenumber; /* input line counter */ @@ -151,30 +151,30 @@ public class LexState extends Constants { final static Hashtable RESERVED = new Hashtable(); static { for (int i = 0; i < NUM_RESERVED; i++) { - LuaString ts = (LuaString) LuaValue.valueOf(luaX_tokens[i]); - RESERVED.put(ts, new Integer(FIRST_RESERVED+i)); + LuaString ts = LuaValue.valueOf(luaX_tokens[i]); + RESERVED.put(ts, Integer.valueOf(FIRST_RESERVED+i)); } } private boolean isalnum(int c) { - return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c == '_'); + return c >= '0' && c <= '9' || c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c == '_'; // return Character.isLetterOrDigit(c); } private boolean isalpha(int c) { - return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); + return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z'; } private boolean isdigit(int c) { - return (c >= '0' && c <= '9'); + return c >= '0' && c <= '9'; } private boolean isxdigit(int c) { - return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'); + return c >= '0' && c <= '9' || c >= 'a' && c <= 'f' || c >= 'A' && c <= 'F'; } private boolean isspace(int c) { - return (c >= 0 && c <= ' '); + return c >= 0 && c <= ' '; } public LexState(LuaC.CompileState state, InputStream stream) { @@ -209,8 +209,7 @@ public class LexState extends Constants { String token2str(int token) { if (token < FIRST_RESERVED) { - return iscntrl(token)? L.pushfstring("char(" + ((int) token) + ")") - : L.pushfstring(String.valueOf((char) token)); + return iscntrl(token)? L.pushfstring("char(" + token + ")"): L.pushfstring(String.valueOf((char) token)); } else { return luaX_tokens[token-FIRST_RESERVED]; } @@ -299,7 +298,7 @@ public class LexState extends Constants { void buffreplace(char from, char to) { int n = nbuff; char[] p = buff; - while ( (--n) >= 0 ) + while ( --n >= 0 ) if (p[n] == from) p[n] = to; } @@ -316,11 +315,7 @@ public class LexState extends Constants { ++s; } /* Check for "0x" */ - if (s+2 >= c.length) - return LuaValue.ZERO; - if (c[s++] != '0') - return LuaValue.ZERO; - if (c[s] != 'x' && c[s] != 'X') + if (s+2 >= c.length || c[s++] != '0' || c[s] != 'x' && c[s] != 'X') return LuaValue.ZERO; ++s; @@ -328,11 +323,11 @@ public class LexState extends Constants { double m = 0; int e = 0; while ( s < c.length && isxdigit(c[s]) ) - m = (m*16)+hexvalue(c[s++]); + m = m*16+hexvalue(c[s++]); if (s < c.length && c[s] == '.') { ++s; // skip dot while ( s < c.length && isxdigit(c[s]) ) { - m = (m*16)+hexvalue(c[s++]); + m = m*16+hexvalue(c[s++]); e -= 4; // Each fractional part shifts right by 2^4 } } @@ -396,7 +391,7 @@ public class LexState extends Constants { save_and_next(); count++; } - return (current == s)? count: (-count)-1; + return current == s? count: (-count)-1; } void read_long_string(SemInfo seminfo, int sep) { @@ -407,7 +402,7 @@ public class LexState extends Constants { for (boolean endloop = false; !endloop;) { switch (current) { case EOZ: - lexerror((seminfo != null)? "unfinished long string": "unfinished long comment", TK_EOS); + lexerror(seminfo != null? "unfinished long string": "unfinished long comment", TK_EOS); break; /* to avoid warnings */ case '[': { if (skip_sep() == sep) { @@ -462,7 +457,7 @@ public class LexState extends Constants { nextChar(); int c2 = current; if (!isxdigit(c1) || !isxdigit(c2)) - lexerror("hexadecimal digit expected 'x" + ((char) c1) + ((char) c2), TK_STRING); + lexerror("hexadecimal digit expected 'x" + (char) c1 + (char) c2, TK_STRING); return (hexvalue(c1)<<4)+hexvalue(c2); } @@ -529,7 +524,7 @@ public class LexState extends Constants { int i = 0; c = 0; do { - c = 10*c+(current-'0'); + c = 10*c+current-'0'; nextChar(); } while ( ++i < 3 && isdigit(current) ); if (c > UCHAR_MAX) @@ -724,11 +719,11 @@ public class LexState extends Constants { // ============================================================= static final boolean vkisvar(final int k) { - return (VLOCAL <= (k) && (k) <= VINDEXED); + return VLOCAL <= k && k <= VINDEXED; } static final boolean vkisinreg(final int k) { - return ((k) == VNONRELOC || (k) == VLOCAL); + return k == VNONRELOC || k == VLOCAL; } static class expdesc { @@ -744,9 +739,9 @@ public class LexState extends Constants { public void setNval(LuaValue r) { _nval = r; } public LuaValue nval() { - return (_nval == null? LuaInteger.valueOf(info): _nval); + return _nval == null? LuaInteger.valueOf(info): _nval; } - }; + } final U u = new U(); final IntPtr t = new IntPtr(); /* patch list of `exit when true' */ @@ -760,11 +755,11 @@ public class LexState extends Constants { } boolean hasjumps() { - return (t.i != f.i); + return t.i != f.i; } boolean isnumeral() { - return (k == VKNUM && t.i == NO_JUMP && f.i == NO_JUMP); + return k == VKNUM && t.i == NO_JUMP && f.i == NO_JUMP; } public void setvalue(expdesc other) { @@ -786,7 +781,7 @@ public class LexState extends Constants { Vardesc(int idx) { this.idx = (short) idx; } - }; + } /* description of pending goto statements and label statements */ static class Labeldesc { @@ -801,7 +796,7 @@ public class LexState extends Constants { this.line = line; this.nactvar = nactvar; } - }; + } /* dynamic structures used by the parser */ static class Dyndata { @@ -811,10 +806,10 @@ public class LexState extends Constants { int n_gt = 0; Labeldesc[] label; /* list of active labels */ int n_label = 0; - }; + } boolean hasmultret(int k) { - return ((k) == VCALL || (k) == VVARARG); + return k == VCALL || k == VVARARG; } /*---------------------------------------------------------------------- @@ -860,7 +855,7 @@ public class LexState extends Constants { } void check_condition(boolean c, String msg) { - if (!(c)) + if (!c) syntaxerror(msg); } @@ -902,7 +897,7 @@ public class LexState extends Constants { void new_localvar(LuaString name) { int reg = registerlocalvar(name); - fs.checklimit(dyd.n_actvar+1, FuncState.LUAI_MAXVARS, "local variables"); + fs.checklimit(dyd.n_actvar+1, Constants.LUAI_MAXVARS, "local variables"); if (dyd.actvar == null || dyd.n_actvar+1 > dyd.actvar.length) dyd.actvar = realloc(dyd.actvar, Math.max(1, dyd.n_actvar*2)); dyd.actvar[dyd.n_actvar++] = new Vardesc(reg); @@ -1138,7 +1133,7 @@ public class LexState extends Constants { int nh; /* total number of `record' elements */ int na; /* total number of array elements */ int tostore; /* number of array elements pending to be stored */ - }; + } void recfield(ConsControl cc) { /* recfield -> (NAME | `['exp1`]') = exp1 */ @@ -1219,13 +1214,13 @@ public class LexState extends Constants { static int luaO_int2fb(int x) { int e = 0; /* expoent */ while ( x >= 16 ) { - x = (x+1)>>1; + x = x+1>>1; e++; } if (x < 8) return x; else - return ((e+1)<<3) | (((int) x)-8); + return e+1<<3 | x-8; } /* }====================================================================== */ @@ -1252,7 +1247,7 @@ public class LexState extends Constants { default: this.syntaxerror(" or " + LUA_QL("...") + " expected"); } - } while ( (f.is_vararg == 0) && this.testnext(',') ); + } while ( f.is_vararg == 0 && this.testnext(',') ); } this.adjustlocalvars(nparams); f.numparams = fs.nactvar; @@ -1359,8 +1354,7 @@ public class LexState extends Constants { return; } default: { - this.syntaxerror("unexpected symbol " + t.token + " (" + ((char) t.token) + ")"); - return; + this.syntaxerror("unexpected symbol " + t.token + " (" + (char) t.token + ")"); } } } @@ -1513,7 +1507,7 @@ public class LexState extends Constants { left = (byte) i; right = (byte) j; } - }; + } static Priority[] priority = { /* ORDER OPR */ new Priority(6, 6), new Priority(6, 6), new Priority(7, 7), new Priority(7, 7), @@ -1601,7 +1595,7 @@ public class LexState extends Constants { LHS_assign prev; /* variable (global, local, upvalue, or indexed) */ expdesc v = new expdesc(); - }; + } /* ** check whether, in an assignment to a local variable, the local variable @@ -1611,7 +1605,7 @@ public class LexState extends Constants { */ void check_conflict(LHS_assign lh, expdesc v) { FuncState fs = this.fs; - short extra = (short) fs.freereg; /* eventual position to save local variable */ + short extra = fs.freereg; /* eventual position to save local variable */ boolean conflict = false; for (; lh != null; lh = lh.prev) { if (lh.v.k == VINDEXED) { @@ -1630,7 +1624,7 @@ public class LexState extends Constants { } if (conflict) { /* copy upvalue/local value to a temporary (in position 'extra') */ - int op = (v.k == VLOCAL)? Lua.OP_MOVE: Lua.OP_GETUPVAL; + int op = v.k == VLOCAL? Lua.OP_MOVE: Lua.OP_GETUPVAL; fs.codeABC(op, extra, v.u.info, 0); fs.reserveregs(1); } diff --git a/luaj-core/src/main/java/org/luaj/vm2/compiler/LuaC.java b/luaj-core/src/main/java/org/luaj/vm2/compiler/LuaC.java index 0728bade..fadc20a3 100644 --- a/luaj-core/src/main/java/org/luaj/vm2/compiler/LuaC.java +++ b/luaj-core/src/main/java/org/luaj/vm2/compiler/LuaC.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 @@ -35,24 +35,24 @@ import org.luaj.vm2.lib.BaseLib; /** * Compiler for Lua. - * + * *

    * Compiles lua source files into lua bytecode within a {@link Prototype}, loads * lua binary files directly into a {@link Prototype}, and optionaly * instantiates a {@link LuaClosure} around the result using a user-supplied * environment. - * + * *

    * Implements the {@link org.luaj.vm2.Globals.Compiler} interface for loading * initialized chunks, which is an interface common to lua bytecode compiling * and java bytecode compiling. - * + * *

    * The {@link LuaC} compiler is installed by default by both the * {@link org.luaj.vm2.lib.jse.JsePlatform} and * {@link org.luaj.vm2.lib.jme.JmePlatform} classes, so in the following * example, the default {@link LuaC} compiler will be used: - * + * *

      * {
      * 	@code
    @@ -60,15 +60,15 @@ import org.luaj.vm2.lib.BaseLib;
      * 	globals.load(new StringReader("print 'hello'"), "main.lua").call();
      * }
      * 
    - * + * * To load the LuaC compiler manually, use the install method: - * + * *
      *  {@code
      * LuaC.install(globals);
      * }
      * 
    - * + * * @see #install(Globals) * @see Globals#compiler * @see Globals#loader @@ -87,7 +87,7 @@ public class LuaC extends Constants implements Globals.Compiler, Globals.Loader /** * Install the compiler so that LoadState will first try to use it when * handed bytes that are not already a compiled lua chunk. - * + * * @param globals the Globals into which this is to be installed. */ public static void install(Globals globals) { @@ -99,17 +99,19 @@ public class LuaC extends Constants implements Globals.Compiler, Globals.Loader /** * Compile lua source into a Prototype. - * + * * @param stream InputStream representing the text source conforming to * lua source syntax. * @param chunkname String name of the chunk to use. * @return Prototype representing the lua chunk for this source. * @throws IOException */ + @Override public Prototype compile(InputStream stream, String chunkname) throws IOException { - return (new CompileState()).luaY_parser(stream, chunkname); + return new CompileState().luaY_parser(stream, chunkname); } + @Override public LuaFunction load(Prototype prototype, String chunkname, LuaValue env) throws IOException { return new LuaClosure(prototype, env); } @@ -119,13 +121,14 @@ public class LuaC extends Constants implements Globals.Compiler, Globals.Loader * LuaC.compile(InputStream, String) and construct LuaClosure * directly. */ + @Deprecated public LuaValue load(InputStream stream, String chunkname, Globals globals) throws IOException { return new LuaClosure(compile(stream, chunkname), globals); } static class CompileState { - int nCcalls = 0; - private Hashtable strings = new Hashtable(); + int nCcalls = 0; + private final Hashtable strings = new Hashtable(); protected CompileState() {} @@ -135,15 +138,15 @@ public class LuaC extends Constants implements Globals.Compiler, Globals.Loader FuncState funcstate = new FuncState(); // lexstate.buff = buff; lexstate.fs = funcstate; - lexstate.setinput(this, z.read(), z, (LuaString) LuaValue.valueOf(name)); + lexstate.setinput(this, z.read(), z, LuaValue.valueOf(name)); /* main func. is always vararg */ funcstate.f = new Prototype(); - funcstate.f.source = (LuaString) LuaValue.valueOf(name); + funcstate.f.source = LuaValue.valueOf(name); lexstate.mainfunc(funcstate); - LuaC._assert(funcstate.prev == null); + Constants._assert(funcstate.prev == null); /* all scopes should be correctly finished */ - LuaC._assert(lexstate.dyd == null - || (lexstate.dyd.n_actvar == 0 && lexstate.dyd.n_gt == 0 && lexstate.dyd.n_label == 0)); + Constants._assert(lexstate.dyd == null + || lexstate.dyd.n_actvar == 0 && lexstate.dyd.n_gt == 0 && lexstate.dyd.n_label == 0); return funcstate.f; } diff --git a/luaj-core/src/main/java/org/luaj/vm2/lib/BaseLib.java b/luaj-core/src/main/java/org/luaj/vm2/lib/BaseLib.java index 3c5c2b65..72d20aa2 100644 --- a/luaj-core/src/main/java/org/luaj/vm2/lib/BaseLib.java +++ b/luaj-core/src/main/java/org/luaj/vm2/lib/BaseLib.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 @@ -50,7 +50,7 @@ import org.luaj.vm2.Varargs; * Typically, this library is included as part of a call to either * {@link org.luaj.vm2.lib.jse.JsePlatform#standardGlobals()} or * {@link org.luaj.vm2.lib.jme.JmePlatform#standardGlobals()} - * + * *
      * {
      * 	@code
    @@ -62,7 +62,7 @@ import org.luaj.vm2.Varargs;
      * For special cases where the smallest possible footprint is desired, a minimal
      * set of libraries could be loaded directly via {@link Globals#load(LuaValue)}
      * using code such as:
    - * 
    + *
      * 
      * {
      * 	@code
    @@ -71,12 +71,12 @@ import org.luaj.vm2.Varargs;
      * 	globals.get("print").call(LuaValue.valueOf("hello, world"));
      * }
      * 
    - * + * * Doing so will ensure the library is properly initialized and loaded into the * globals table. *

    * This is a direct port of the corresponding library in C. - * + * * @see org.luaj.vm2.lib.jse.JseBaseLib * @see ResourceFinder * @see Globals#finder @@ -93,11 +93,12 @@ public class BaseLib extends TwoArgFunction implements ResourceFinder { /** * Perform one-time initialization on the library by adding base functions * to the supplied environment, and returning it as the return value. - * + * * @param modname the module name supplied if this is loaded via 'require'. * @param env the environment to load into, which must be a Globals * instance. */ + @Override public LuaValue call(LuaValue modname, LuaValue env) { globals = env.checkglobals(); globals.finder = this; @@ -134,15 +135,17 @@ public class BaseLib extends TwoArgFunction implements ResourceFinder { /** * ResourceFinder implementation - * + * * Tries to open the file as a resource, which can work for JSE and JME. */ + @Override public InputStream findResource(String filename) { return getClass().getResourceAsStream(filename.startsWith("/")? filename: "/" + filename); } // "assert", // ( v [,message] ) -> v, message | ERR static final class _assert extends VarArgFunction { + @Override public Varargs invoke(Varargs args) { if (!args.arg1().toboolean()) error(args.narg() > 1? args.optjstring(2, "assertion failed!"): "assertion failed!"); @@ -152,6 +155,7 @@ public class BaseLib extends TwoArgFunction implements ResourceFinder { // "collectgarbage", // ( opt [,arg] ) -> value static final class collectgarbage extends VarArgFunction { + @Override public Varargs invoke(Varargs args) { String s = args.optjstring(1, "collect"); if ("collect".equals(s)) { @@ -173,6 +177,7 @@ public class BaseLib extends TwoArgFunction implements ResourceFinder { // "dofile", // ( filename ) -> result1, ... final class dofile extends VarArgFunction { + @Override public Varargs invoke(Varargs args) { args.argcheck(args.isstring(1) || args.isnil(1), 1, "filename must be string or nil"); String filename = args.isstring(1)? args.tojstring(1): null; @@ -184,6 +189,7 @@ public class BaseLib extends TwoArgFunction implements ResourceFinder { // "error", // ( message [,level] ) -> ERR static final class error extends TwoArgFunction { + @Override public LuaValue call(LuaValue arg1, LuaValue arg2) { if (arg1.isnil()) throw new LuaError(NIL); @@ -195,10 +201,12 @@ public class BaseLib extends TwoArgFunction implements ResourceFinder { // "getmetatable", // ( object ) -> table static final class getmetatable extends LibFunction { + @Override public LuaValue call() { return argerror(1, "value expected"); } + @Override public LuaValue call(LuaValue arg) { LuaValue mt = arg.getmetatable(); return mt != null? mt.rawget(METATABLE).optvalue(mt): NIL; @@ -207,6 +215,7 @@ public class BaseLib extends TwoArgFunction implements ResourceFinder { // "load", // ( ld [, source [, mode [, env]]] ) -> chunk | nil, msg final class load extends VarArgFunction { + @Override public Varargs invoke(Varargs args) { LuaValue ld = args.arg1(); if (!ld.isstring() && !ld.isfunction()) { @@ -223,6 +232,7 @@ public class BaseLib extends TwoArgFunction implements ResourceFinder { // "loadfile", // ( [filename [, mode [, env]]] ) -> chunk | nil, msg final class loadfile extends VarArgFunction { + @Override public Varargs invoke(Varargs args) { args.argcheck(args.isstring(1) || args.isnil(1), 1, "filename must be string or nil"); String filename = args.isstring(1)? args.tojstring(1): null; @@ -234,6 +244,7 @@ public class BaseLib extends TwoArgFunction implements ResourceFinder { // "pcall", // (f, arg1, ...) -> status, result1, ... final class pcall extends VarArgFunction { + @Override public Varargs invoke(Varargs args) { LuaValue func = args.checkvalue(1); if (globals != null && globals.debuglib != null) @@ -261,6 +272,7 @@ public class BaseLib extends TwoArgFunction implements ResourceFinder { this.baselib = baselib; } + @Override public Varargs invoke(Varargs args) { LuaValue tostring = globals.get("tostring"); for (int i = 1, n = args.narg(); i <= n; i++) { @@ -276,14 +288,17 @@ public class BaseLib extends TwoArgFunction implements ResourceFinder { // "rawequal", // (v1, v2) -> boolean static final class rawequal extends LibFunction { + @Override public LuaValue call() { return argerror(1, "value expected"); } + @Override public LuaValue call(LuaValue arg) { return argerror(2, "value expected"); } + @Override public LuaValue call(LuaValue arg1, LuaValue arg2) { return valueOf(arg1.raweq(arg2)); } @@ -291,10 +306,12 @@ public class BaseLib extends TwoArgFunction implements ResourceFinder { // "rawget", // (table, index) -> value static final class rawget extends TableLibFunction { + @Override public LuaValue call(LuaValue arg) { return argerror(2, "value expected"); } + @Override public LuaValue call(LuaValue arg1, LuaValue arg2) { return arg1.checktable().rawget(arg2); } @@ -302,6 +319,7 @@ public class BaseLib extends TwoArgFunction implements ResourceFinder { // "rawlen", // (v) -> value static final class rawlen extends LibFunction { + @Override public LuaValue call(LuaValue arg) { return valueOf(arg.rawlen()); } @@ -309,14 +327,17 @@ public class BaseLib extends TwoArgFunction implements ResourceFinder { // "rawset", // (table, index, value) -> table static final class rawset extends TableLibFunction { + @Override public LuaValue call(LuaValue table) { return argerror(2, "value expected"); } + @Override public LuaValue call(LuaValue table, LuaValue index) { return argerror(3, "value expected"); } + @Override public LuaValue call(LuaValue table, LuaValue index, LuaValue value) { LuaTable t = table.checktable(); if (!index.isvalidkey()) @@ -328,6 +349,7 @@ public class BaseLib extends TwoArgFunction implements ResourceFinder { // "select", // (f, ...) -> value1, ... static final class select extends VarArgFunction { + @Override public Varargs invoke(Varargs args) { int n = args.narg()-1; if (args.arg1().equals(valueOf("#"))) @@ -341,10 +363,12 @@ public class BaseLib extends TwoArgFunction implements ResourceFinder { // "setmetatable", // (table, metatable) -> table static final class setmetatable extends TableLibFunction { + @Override public LuaValue call(LuaValue table) { return argerror(2, "nil or table expected"); } + @Override public LuaValue call(LuaValue table, LuaValue metatable) { final LuaValue mt0 = table.checktable().getmetatable(); if (mt0 != null && !mt0.rawget(METATABLE).isnil()) @@ -355,10 +379,12 @@ public class BaseLib extends TwoArgFunction implements ResourceFinder { // "tonumber", // (e [,base]) -> value static final class tonumber extends LibFunction { + @Override public LuaValue call(LuaValue e) { return e.tonumber(); } + @Override public LuaValue call(LuaValue e, LuaValue base) { if (base.isnil()) return e.tonumber(); @@ -371,6 +397,7 @@ public class BaseLib extends TwoArgFunction implements ResourceFinder { // "tostring", // (e) -> value static final class tostring extends LibFunction { + @Override public LuaValue call(LuaValue arg) { LuaValue h = arg.metatag(TOSTRING); if (!h.isnil()) @@ -384,6 +411,7 @@ public class BaseLib extends TwoArgFunction implements ResourceFinder { // "type", // (v) -> value static final class type extends LibFunction { + @Override public LuaValue call(LuaValue arg) { return valueOf(arg.typename()); } @@ -391,6 +419,7 @@ public class BaseLib extends TwoArgFunction implements ResourceFinder { // "xpcall", // (f, err) -> result1, ... final class xpcall extends VarArgFunction { + @Override public Varargs invoke(Varargs args) { final LuaThread t = globals.running; final LuaValue preverror = t.errorfunc; @@ -424,6 +453,7 @@ public class BaseLib extends TwoArgFunction implements ResourceFinder { this.next = next; } + @Override public Varargs invoke(Varargs args) { return varargsOf(next, args.checktable(1), NIL); } @@ -433,6 +463,7 @@ public class BaseLib extends TwoArgFunction implements ResourceFinder { static final class ipairs extends VarArgFunction { inext inext = new inext(); + @Override public Varargs invoke(Varargs args) { return varargsOf(inext, args.checktable(1), ZERO); } @@ -440,6 +471,7 @@ public class BaseLib extends TwoArgFunction implements ResourceFinder { // "next" ( table, [index] ) -> next-index, next-value static final class next extends VarArgFunction { + @Override public Varargs invoke(Varargs args) { return args.checktable(1).next(args.arg(2)); } @@ -447,6 +479,7 @@ public class BaseLib extends TwoArgFunction implements ResourceFinder { // "inext" ( table, [int-index] ) -> next-index, next-value static final class inext extends VarArgFunction { + @Override public Varargs invoke(Varargs args) { return args.checktable(1).inext(args.arg(2)); } @@ -454,7 +487,7 @@ public class BaseLib extends TwoArgFunction implements ResourceFinder { /** * Load from a named file, returning the chunk or nil,error of can't load - * + * * @param env * @param mode * @return Varargs containing chunk, or NIL,error-text on error @@ -493,6 +526,7 @@ public class BaseLib extends TwoArgFunction implements ResourceFinder { this.func = func; } + @Override public int read() throws IOException { if (remaining < 0) return -1; diff --git a/luaj-core/src/main/java/org/luaj/vm2/lib/Bit32Lib.java b/luaj-core/src/main/java/org/luaj/vm2/lib/Bit32Lib.java index f15c2efc..477e7317 100644 --- a/luaj-core/src/main/java/org/luaj/vm2/lib/Bit32Lib.java +++ b/luaj-core/src/main/java/org/luaj/vm2/lib/Bit32Lib.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 @@ -32,7 +32,7 @@ import org.luaj.vm2.Varargs; * Typically, this library is included as part of a call to either * {@link org.luaj.vm2.lib.jse.JsePlatform#standardGlobals()} or * {@link org.luaj.vm2.lib.jme.JmePlatform#standardGlobals()} - * + * *

      * {
      * 	@code
    @@ -43,7 +43,7 @@ import org.luaj.vm2.Varargs;
      * 

    * To instantiate and use it directly, link it into your globals table via * {@link LuaValue#load(LuaValue)} using code such as: - * + * *

      * {
      * 	@code
    @@ -57,7 +57,7 @@ import org.luaj.vm2.Varargs;
      * 

    * This has been implemented to match as closely as possible the behavior in the * corresponding library in C. - * + * * @see LibFunction * @see org.luaj.vm2.lib.jse.JsePlatform * @see org.luaj.vm2.lib.jme.JmePlatform @@ -74,11 +74,12 @@ public class Bit32Lib extends TwoArgFunction { * containing the library functions, adding that table to the supplied * environment, adding the table to package.loaded, and returning table as * the return value. - * + * * @param modname the module name supplied if this is loaded via 'require'. * @param env the environment to load into, which must be a Globals * instance. */ + @Override public LuaValue call(LuaValue modname, LuaValue env) { LuaTable t = new LuaTable(); bind(t, Bit32LibV.class, new String[] { "band", "bnot", "bor", "btest", "bxor", "extract", "replace" }); @@ -90,6 +91,7 @@ public class Bit32Lib extends TwoArgFunction { } static final class Bit32LibV extends VarArgFunction { + @Override public Varargs invoke(Varargs args) { switch (opcode) { case 0: @@ -113,6 +115,7 @@ public class Bit32Lib extends TwoArgFunction { static final class Bit32Lib2 extends TwoArgFunction { + @Override public LuaValue call(LuaValue arg1, LuaValue arg2) { switch (opcode) { case 0: @@ -200,7 +203,7 @@ public class Bit32Lib extends TwoArgFunction { return rrotate(x, -disp); } else { disp = disp & 31; - return bitsToValue((x<>>(32-disp))); + return bitsToValue(x<>>32-disp); } } @@ -209,7 +212,7 @@ public class Bit32Lib extends TwoArgFunction { return lrotate(x, -disp); } else { disp = disp & 31; - return bitsToValue((x>>>disp) | (x<<(32-disp))); + return bitsToValue(x>>>disp | x<<32-disp); } } @@ -223,7 +226,7 @@ public class Bit32Lib extends TwoArgFunction { if (field+width > 32) { error("trying to access non-existent bits"); } - return bitsToValue((n>>>field) & (-1>>>(32-width))); + return bitsToValue(n>>>field & -1>>>32-width); } static LuaValue replace(int n, int v, int field, int width) { @@ -236,12 +239,12 @@ public class Bit32Lib extends TwoArgFunction { if (field+width > 32) { error("trying to access non-existent bits"); } - int mask = (-1>>>(32-width))<>>32-width< * { * @code @@ -52,7 +52,7 @@ import org.luaj.vm2.Varargs; *

    * To instantiate and use it directly, link it into your globals table via * {@link LuaValue#load(LuaValue)} using code such as: - * + * *

      * {
      * 	@code
    @@ -64,7 +64,7 @@ import org.luaj.vm2.Varargs;
      * }
      * 
    *

    - * + * * @see LibFunction * @see org.luaj.vm2.lib.jse.JsePlatform * @see org.luaj.vm2.lib.jme.JmePlatform @@ -82,11 +82,12 @@ public class CoroutineLib extends TwoArgFunction { * containing the library functions, adding that table to the supplied * environment, adding the table to package.loaded, and returning table as * the return value. - * + * * @param modname the module name supplied if this is loaded via 'require'. * @param env the environment to load into, which must be a Globals * instance. */ + @Override public LuaValue call(LuaValue modname, LuaValue env) { globals = env.checkglobals(); LuaTable coroutine = new LuaTable(); @@ -103,12 +104,14 @@ public class CoroutineLib extends TwoArgFunction { } final class create extends LibFunction { + @Override public LuaValue call(LuaValue f) { return new LuaThread(globals, f.checkfunction()); } } static final class resume extends VarArgFunction { + @Override public Varargs invoke(Varargs args) { final LuaThread t = args.checkthread(1); return t.resume(args.subargs(2)); @@ -116,6 +119,7 @@ public class CoroutineLib extends TwoArgFunction { } final class running extends VarArgFunction { + @Override public Varargs invoke(Varargs args) { final LuaThread r = globals.running; return varargsOf(r, valueOf(r.isMainThread())); @@ -123,6 +127,7 @@ public class CoroutineLib extends TwoArgFunction { } static final class status extends LibFunction { + @Override public LuaValue call(LuaValue t) { LuaThread lt = t.checkthread(); return valueOf(lt.getStatus()); @@ -130,12 +135,14 @@ public class CoroutineLib extends TwoArgFunction { } final class yield extends VarArgFunction { + @Override public Varargs invoke(Varargs args) { return globals.yield(args); } } final class wrap extends LibFunction { + @Override public LuaValue call(LuaValue f) { final LuaValue func = f.checkfunction(); final LuaThread thread = new LuaThread(globals, func); @@ -150,6 +157,7 @@ public class CoroutineLib extends TwoArgFunction { this.luathread = luathread; } + @Override public Varargs invoke(Varargs args) { final Varargs result = luathread.resume(args); if (result.arg1().toboolean()) { diff --git a/luaj-core/src/main/java/org/luaj/vm2/lib/DebugLib.java b/luaj-core/src/main/java/org/luaj/vm2/lib/DebugLib.java index 959b71e3..20349c89 100644 --- a/luaj-core/src/main/java/org/luaj/vm2/lib/DebugLib.java +++ b/luaj-core/src/main/java/org/luaj/vm2/lib/DebugLib.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 @@ -52,7 +52,7 @@ import org.luaj.vm2.Varargs; * Typically, this library is included as part of a call to either * {@link org.luaj.vm2.lib.jse.JsePlatform#debugGlobals()} or * {@link org.luaj.vm2.lib.jme.JmePlatform#debugGlobals()} - * + * *

      * {
      * 	@code
    @@ -63,7 +63,7 @@ import org.luaj.vm2.Varargs;
      * 

    * To instantiate and use it directly, link it into your globals table via * {@link LuaValue#load(LuaValue)} using code such as: - * + * *

      * {
      * 	@code
    @@ -78,7 +78,7 @@ import org.luaj.vm2.Varargs;
      * This library exposes the entire state of lua code, and provides method to see
      * and modify all underlying lua values within a Java VM so should not be
      * exposed to client code in a shared server environment.
    - * 
    + *
      * @see LibFunction
      * @see org.luaj.vm2.lib.jse.JsePlatform
      * @see org.luaj.vm2.lib.jme.JmePlatform
    @@ -90,11 +90,11 @@ public class DebugLib extends TwoArgFunction {
     	public static boolean TRACE;
     	static {
     		try {
    -			CALLS = (null != System.getProperty("CALLS"));
    +			CALLS = null != System.getProperty("CALLS");
     		} catch (Exception e) {
     		}
     		try {
    -			TRACE = (null != System.getProperty("TRACE"));
    +			TRACE = null != System.getProperty("TRACE");
     		} catch (Exception e) {
     		}
     	}
    @@ -128,11 +128,12 @@ public class DebugLib extends TwoArgFunction {
     	 * containing the library functions, adding that table to the supplied
     	 * environment, adding the table to package.loaded, and returning table as
     	 * the return value.
    -	 * 
    +	 *
     	 * @param modname the module name supplied if this is loaded via 'require'.
     	 * @param env     the environment to load into, which must be a Globals
     	 *                instance.
     	 */
    +	@Override
     	public LuaValue call(LuaValue modname, LuaValue env) {
     		globals = env.checkglobals();
     		globals.debuglib = this;
    @@ -161,6 +162,7 @@ public class DebugLib extends TwoArgFunction {
     
     	// debug.debug()
     	static final class debug extends ZeroArgFunction {
    +		@Override
     		public LuaValue call() {
     			return NONE;
     		}
    @@ -168,6 +170,7 @@ public class DebugLib extends TwoArgFunction {
     
     	// debug.gethook ([thread])
     	final class gethook extends VarArgFunction {
    +		@Override
     		public Varargs invoke(Varargs args) {
     			LuaThread t = args.narg() > 0? args.checkthread(1): globals.running;
     			LuaThread.State s = t.state;
    @@ -178,6 +181,7 @@ public class DebugLib extends TwoArgFunction {
     
     	//	debug.getinfo ([thread,] f [, what])
     	final class getinfo extends VarArgFunction {
    +		@Override
     		public Varargs invoke(Varargs args) {
     			int a = 1;
     			LuaThread thread = args.isthread(a)? args.checkthread(a++): globals.running;
    @@ -241,6 +245,7 @@ public class DebugLib extends TwoArgFunction {
     
     	//	debug.getlocal ([thread,] f, local)
     	final class getlocal extends VarArgFunction {
    +		@Override
     		public Varargs invoke(Varargs args) {
     			int a = 1;
     			LuaThread thread = args.isthread(a)? args.checkthread(a++): globals.running;
    @@ -253,6 +258,7 @@ public class DebugLib extends TwoArgFunction {
     
     	//	debug.getmetatable (value)
     	static final class getmetatable extends LibFunction {
    +		@Override
     		public LuaValue call(LuaValue v) {
     			LuaValue mt = v.getmetatable();
     			return mt != null? mt: NIL;
    @@ -261,6 +267,7 @@ public class DebugLib extends TwoArgFunction {
     
     	//	debug.getregistry ()
     	final class getregistry extends ZeroArgFunction {
    +		@Override
     		public LuaValue call() {
     			return globals;
     		}
    @@ -268,6 +275,7 @@ public class DebugLib extends TwoArgFunction {
     
     	//	debug.getupvalue (f, up)
     	static final class getupvalue extends VarArgFunction {
    +		@Override
     		public Varargs invoke(Varargs args) {
     			LuaValue func = args.checkfunction(1);
     			int up = args.checkint(2);
    @@ -284,6 +292,7 @@ public class DebugLib extends TwoArgFunction {
     
     	//	debug.getuservalue (u)
     	static final class getuservalue extends LibFunction {
    +		@Override
     		public LuaValue call(LuaValue u) {
     			return u.isuserdata()? u: NIL;
     		}
    @@ -291,6 +300,7 @@ public class DebugLib extends TwoArgFunction {
     
     	// debug.sethook ([thread,] hook, mask [, count])
     	final class sethook extends VarArgFunction {
    +		@Override
     		public Varargs invoke(Varargs args) {
     			int a = 1;
     			LuaThread t = args.isthread(a)? args.checkthread(a++): globals.running;
    @@ -322,6 +332,7 @@ public class DebugLib extends TwoArgFunction {
     
     	//	debug.setlocal ([thread,] level, local, value)
     	final class setlocal extends VarArgFunction {
    +		@Override
     		public Varargs invoke(Varargs args) {
     			int a = 1;
     			LuaThread thread = args.isthread(a)? args.checkthread(a++): globals.running;
    @@ -335,6 +346,7 @@ public class DebugLib extends TwoArgFunction {
     
     	//	debug.setmetatable (value, table)
     	static final class setmetatable extends TwoArgFunction {
    +		@Override
     		public LuaValue call(LuaValue value, LuaValue table) {
     			LuaValue mt = table.opttable(null);
     			switch (value.type()) {
    @@ -365,6 +377,7 @@ public class DebugLib extends TwoArgFunction {
     
     	//	debug.setupvalue (f, up, value)
     	static final class setupvalue extends VarArgFunction {
    +		@Override
     		public Varargs invoke(Varargs args) {
     			LuaValue func = args.checkfunction(1);
     			int up = args.checkint(2);
    @@ -383,6 +396,7 @@ public class DebugLib extends TwoArgFunction {
     
     	//	debug.setuservalue (udata, value)
     	static final class setuservalue extends VarArgFunction {
    +		@Override
     		public Varargs invoke(Varargs args) {
     			Object o = args.checkuserdata(1);
     			LuaValue v = args.checkvalue(2);
    @@ -395,6 +409,7 @@ public class DebugLib extends TwoArgFunction {
     
     	//	debug.traceback ([thread,] [message [, level]])
     	final class traceback extends VarArgFunction {
    +		@Override
     		public Varargs invoke(Varargs args) {
     			int a = 1;
     			LuaThread thread = args.isthread(a)? args.checkthread(a++): globals.running;
    @@ -407,6 +422,7 @@ public class DebugLib extends TwoArgFunction {
     
     	//	debug.upvalueid (f, n)
     	static final class upvalueid extends VarArgFunction {
    +		@Override
     		public Varargs invoke(Varargs args) {
     			LuaValue func = args.checkfunction(1);
     			int up = args.checkint(2);
    @@ -422,6 +438,7 @@ public class DebugLib extends TwoArgFunction {
     
     	//	debug.upvaluejoin (f1, n1, f2, n2)
     	static final class upvaluejoin extends VarArgFunction {
    +		@Override
     		public Varargs invoke(Varargs args) {
     			LuaClosure f1 = args.checkclosure(1);
     			int n1 = args.checkint(2);
    @@ -536,7 +553,7 @@ public class DebugLib extends TwoArgFunction {
     				this.source = p.source != null? p.source.tojstring(): "=?";
     				this.linedefined = p.linedefined;
     				this.lastlinedefined = p.lastlinedefined;
    -				this.what = (this.linedefined == 0)? "main": "Lua";
    +				this.what = this.linedefined == 0? "main": "Lua";
     				this.short_src = p.shortsource();
     			} else {
     				this.source = "=[Java]";
    @@ -593,7 +610,7 @@ public class DebugLib extends TwoArgFunction {
     
     		/**
     		 * Get the traceback starting at a specific level.
    -		 * 
    +		 *
     		 * @param level
     		 * @return String containing the traceback.
     		 */
    @@ -886,9 +903,9 @@ public class DebugLib extends TwoArgFunction {
     			case Lua.OP_GETTABLE: {
     				int k = Lua.GETARG_C(i); /* key index */
     				int t = Lua.GETARG_B(i); /* table index */
    -				LuaString vn = (Lua.GET_OPCODE(i) == Lua.OP_GETTABLE) /* name of indexed variable */
    +				LuaString vn = Lua.GET_OPCODE(i) == Lua.OP_GETTABLE /* name of indexed variable */
     					? p.getlocalname(t+1, pc)
    -					: (t < p.upvalues.length? p.upvalues[t].name: QMARK);
    +					: t < p.upvalues.length? p.upvalues[t].name: QMARK;
     				String jname = kname(p, pc, k);
     				return new NameWhat(jname, vn != null && vn.eq_b(ENV)? "global": "field");
     			}
    @@ -899,7 +916,7 @@ public class DebugLib extends TwoArgFunction {
     			}
     			case Lua.OP_LOADK:
     			case Lua.OP_LOADKX: {
    -				int b = (Lua.GET_OPCODE(i) == Lua.OP_LOADK)? Lua.GETARG_Bx(i): Lua.GETARG_Ax(p.code[pc+1]);
    +				int b = Lua.GET_OPCODE(i) == Lua.OP_LOADK? Lua.GETARG_Bx(i): Lua.GETARG_Ax(p.code[pc+1]);
     				if (p.k[b].isstring()) {
     					name = p.k[b].strvalue();
     					return new NameWhat(name.tojstring(), "constant");
    @@ -976,7 +993,7 @@ public class DebugLib extends TwoArgFunction {
     				break;
     			}
     			case Lua.OP_SETLIST: { // Lua.testAMode(Lua.OP_SETLIST) == false
    -				if (((i>>14) & 0x1ff) == 0)
    +				if ((i>>14 & 0x1ff) == 0)
     					pc++; // if c == 0 then c stored in next op -> skip
     				break;
     			}
    diff --git a/luaj-core/src/main/java/org/luaj/vm2/lib/IoLib.java b/luaj-core/src/main/java/org/luaj/vm2/lib/IoLib.java
    index 26c81b88..9983c0ec 100644
    --- a/luaj-core/src/main/java/org/luaj/vm2/lib/IoLib.java
    +++ b/luaj-core/src/main/java/org/luaj/vm2/lib/IoLib.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
    @@ -47,7 +47,7 @@ import org.luaj.vm2.Varargs;
      * Typically, this library is included as part of a call to either
      * {@link org.luaj.vm2.lib.jse.JsePlatform#standardGlobals()} or
      * {@link org.luaj.vm2.lib.jme.JmePlatform#standardGlobals()}
    - * 
    + *
      * 
      * {
      * 	@code
    @@ -55,7 +55,7 @@ import org.luaj.vm2.Varargs;
      * 	globals.get("io").get("write").call(LuaValue.valueOf("hello, world\n"));
      * }
      * 
    - * + * * In this example the platform-specific {@link org.luaj.vm2.lib.jse.JseIoLib} * library will be loaded, which will include the base functionality provided by * this class, whereas the {@link org.luaj.vm2.lib.jse.JsePlatform} would load @@ -63,7 +63,7 @@ import org.luaj.vm2.Varargs; *

    * To instantiate and use it directly, link it into your globals table via * {@link LuaValue#load(LuaValue)} using code such as: - * + * *

      * {
      * 	@code
    @@ -77,7 +77,7 @@ import org.luaj.vm2.Varargs;
      * 

    * This has been implemented to match as closely as possible the behavior in the * corresponding library in C. - * + * * @see LibFunction * @see org.luaj.vm2.lib.jse.JsePlatform * @see org.luaj.vm2.lib.jme.JmePlatform @@ -86,35 +86,35 @@ import org.luaj.vm2.Varargs; * @see http://www.lua.org/manual/5.1/manual.html#5.7 */ -abstract public class IoLib extends TwoArgFunction { +public abstract class IoLib extends TwoArgFunction { - abstract protected class File extends LuaValue { - abstract public void write(LuaString string) throws IOException; + protected abstract class File extends LuaValue { + public abstract void write(LuaString string) throws IOException; - abstract public void flush() throws IOException; + public abstract void flush() throws IOException; - abstract public boolean isstdfile(); + public abstract boolean isstdfile(); - abstract public void close() throws IOException; + public abstract void close() throws IOException; - abstract public boolean isclosed(); + public abstract boolean isclosed(); // returns new position - abstract public int seek(String option, int bytecount) throws IOException; + public abstract int seek(String option, int bytecount) throws IOException; - abstract public void setvbuf(String mode, int size); + public abstract void setvbuf(String mode, int size); // get length remaining to read - abstract public int remaining() throws IOException; + public abstract int remaining() throws IOException; // peek ahead one character - abstract public int peek() throws IOException, EOFException; + public abstract int peek() throws IOException, EOFException; // return char if read, -1 if eof, throw IOException on other exception - abstract public int read() throws IOException, EOFException; + public abstract int read() throws IOException, EOFException; // return number of bytes read if positive, false if eof, throw IOException on other exception - abstract public int read(byte[] bytes, int offset, int length) throws IOException; + public abstract int read(byte[] bytes, int offset, int length) throws IOException; public boolean eof() throws IOException { try { @@ -125,24 +125,29 @@ abstract public class IoLib extends TwoArgFunction { } // delegate method access to file methods table + @Override public LuaValue get(LuaValue key) { return filemethods.get(key); } // essentially a userdata instance + @Override public int type() { return LuaValue.TUSERDATA; } + @Override public String typename() { return "userdata"; } // displays as "file" type + @Override public String tojstring() { return "file: " + Integer.toHexString(hashCode()); } + @Override public void finalize() { if (!isclosed()) { try { @@ -164,7 +169,7 @@ abstract public class IoLib extends TwoArgFunction { /** * Wrap the standard input. - * + * * @return File * @throws IOException */ @@ -172,7 +177,7 @@ abstract public class IoLib extends TwoArgFunction { /** * Wrap the standard output. - * + * * @return File * @throws IOException */ @@ -180,7 +185,7 @@ abstract public class IoLib extends TwoArgFunction { /** * Wrap the standard error output. - * + * * @return File * @throws IOException */ @@ -188,7 +193,7 @@ abstract public class IoLib extends TwoArgFunction { /** * Open a file in a particular mode. - * + * * @param filename * @param readMode true if opening in read mode * @param appendMode true if opening in append mode @@ -202,7 +207,7 @@ abstract public class IoLib extends TwoArgFunction { /** * Open a temporary file. - * + * * @return File object if successful * @throws IOException if could not be opened */ @@ -210,7 +215,7 @@ abstract public class IoLib extends TwoArgFunction { /** * Start a new process and return a file for input or output - * + * * @param prog the program to execute * @param mode "r" to read, "w" to write * @return File to read to or write from @@ -260,6 +265,7 @@ abstract public class IoLib extends TwoArgFunction { protected Globals globals; + @Override public LuaValue call(LuaValue modname, LuaValue env) { globals = env.checkglobals(); @@ -310,13 +316,13 @@ abstract public class IoLib extends TwoArgFunction { } public IoLibV(File f, String name, int opcode, IoLib iolib) { - super(); this.f = f; this.name = name; this.opcode = opcode; this.iolib = iolib; } + @Override public Varargs invoke(Varargs args) { try { switch (opcode) { @@ -630,9 +636,7 @@ abstract public class IoLib extends TwoArgFunction { int len = mode.length(); for (int i = 0; i < len; i++) { // [rwa][+]?b* char ch = mode.charAt(i); - if (i == 0 && "rwa".indexOf(ch) >= 0) - continue; - if (i == 1 && ch == '+') + if ((i == 0 && "rwa".indexOf(ch) >= 0) || (i == 1 && ch == '+')) continue; if (i >= 1 && ch == 'b') continue; diff --git a/luaj-core/src/main/java/org/luaj/vm2/lib/LibFunction.java b/luaj-core/src/main/java/org/luaj/vm2/lib/LibFunction.java index 26db9962..5bec4601 100644 --- a/luaj-core/src/main/java/org/luaj/vm2/lib/LibFunction.java +++ b/luaj-core/src/main/java/org/luaj/vm2/lib/LibFunction.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 @@ -57,12 +57,12 @@ import org.luaj.vm2.Varargs; *

    * For example, the following code will implement a library called "hyperbolic" * with two functions, "sinh", and "cosh": - * + * *

      *  {@code
      * import org.luaj.vm2.LuaValue;
      * import org.luaj.vm2.lib.*;
    - * 
    + *
      * public class hyperbolic extends TwoArgFunction {
      *
      *	public hyperbolic() {}
    @@ -80,7 +80,7 @@ import org.luaj.vm2.Varargs;
      *			return LuaValue.valueOf(Math.sinh(x.checkdouble()));
      *		}
      *	}
    - *	
    + *
      *	static class cosh extends OneArgFunction {
      *		public LuaValue call(LuaValue x) {
      *			return LuaValue.valueOf(Math.cosh(x.checkdouble()));
    @@ -89,7 +89,7 @@ import org.luaj.vm2.Varargs;
      *}
      *}
      * 
    - * + * * The default constructor is used to instantiate the library in response to * {@code require 'hyperbolic'} statement, provided it is on Java"s class * path. This instance is then invoked with 2 arguments: the name supplied to @@ -100,7 +100,7 @@ import org.luaj.vm2.Varargs; * 'env' argument. *

    * To test it, a script such as this can be used: - * + * *

      *  {@code
      * local t = require('hyperbolic')
    @@ -115,7 +115,7 @@ import org.luaj.vm2.Varargs;
      * 
    *

    * It should produce something like: - * + * *

      *  {@code
      * t	table: 3dbbd23f
    @@ -152,6 +152,7 @@ abstract public class LibFunction extends LuaFunction {
     	protected LibFunction() {
     	}
     
    +	@Override
     	public String tojstring() {
     		return name != null? "function: " + name: super.tojstring();
     	}
    @@ -161,7 +162,7 @@ abstract public class LibFunction extends LuaFunction {
     	 * 

    * An array of names is provided, and the first name is bound with opcode = * 0, second with 1, etc. - * + * * @param env The environment to apply to each bound function * @param factory the Class to instantiate for each bound function * @param names array of String names, one for each function. @@ -176,7 +177,7 @@ abstract public class LibFunction extends LuaFunction { *

    * An array of names is provided, and the first name is bound with opcode = * {@code firstopcode}, second with {@code firstopcode+1}, etc. - * + * * @param env The environment to apply to each bound function * @param factory the Class to instantiate for each bound function * @param names array of String names, one for each function. @@ -220,18 +221,22 @@ abstract public class LibFunction extends LuaFunction { return new LuaValue[] { v }; } + @Override public LuaValue call() { return argerror(1, "value expected"); } + @Override public LuaValue call(LuaValue a) { return call(); } + @Override public LuaValue call(LuaValue a, LuaValue b) { return call(a); } + @Override public LuaValue call(LuaValue a, LuaValue b, LuaValue c) { return call(a, b); } @@ -240,6 +245,7 @@ abstract public class LibFunction extends LuaFunction { return call(a, b, c); } + @Override public Varargs invoke(Varargs args) { switch (args.narg()) { case 0: diff --git a/luaj-core/src/main/java/org/luaj/vm2/lib/MathLib.java b/luaj-core/src/main/java/org/luaj/vm2/lib/MathLib.java index 67aadf6e..38eed3d4 100644 --- a/luaj-core/src/main/java/org/luaj/vm2/lib/MathLib.java +++ b/luaj-core/src/main/java/org/luaj/vm2/lib/MathLib.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 @@ -54,7 +54,7 @@ import org.luaj.vm2.Varargs; * Typically, this library is included as part of a call to either * {@link org.luaj.vm2.lib.jse.JsePlatform#standardGlobals()} or * {@link org.luaj.vm2.lib.jme.JmePlatform#standardGlobals()} - * + * *

      * {
      * 	@code
    @@ -62,14 +62,14 @@ import org.luaj.vm2.Varargs;
      * 	System.out.println(globals.get("math").get("sqrt").call(LuaValue.valueOf(2)));
      * }
      * 
    - * + * * When using {@link org.luaj.vm2.lib.jse.JsePlatform} as in this example, the * subclass {@link org.luaj.vm2.lib.jse.JseMathLib} will be included, which also * includes this base functionality. *

    * To instantiate and use it directly, link it into your globals table via * {@link LuaValue#load(LuaValue)} using code such as: - * + * *

      * {
      * 	@code
    @@ -80,13 +80,13 @@ import org.luaj.vm2.Varargs;
      * 	System.out.println(globals.get("math").get("sqrt").call(LuaValue.valueOf(2)));
      * }
      * 
    - * + * * Doing so will ensure the library is properly initialized and loaded into the * globals table. *

    * This has been implemented to match as closely as possible the behavior in the * corresponding library in C. - * + * * @see LibFunction * @see org.luaj.vm2.lib.jse.JsePlatform * @see org.luaj.vm2.lib.jme.JmePlatform @@ -116,11 +116,12 @@ public class MathLib extends TwoArgFunction { * containing the library functions, adding that table to the supplied * environment, adding the table to package.loaded, and returning table as * the return value. - * + * * @param modname the module name supplied if this is loaded via 'require'. * @param env the environment to load into, typically a Globals * instance. */ + @Override public LuaValue call(LuaValue modname, LuaValue env) { LuaTable math = new LuaTable(0, 30); math.set("abs", new abs()); @@ -152,6 +153,7 @@ public class MathLib extends TwoArgFunction { } abstract protected static class UnaryOp extends OneArgFunction { + @Override public LuaValue call(LuaValue arg) { return valueOf(call(arg.checkdouble())); } @@ -160,6 +162,7 @@ public class MathLib extends TwoArgFunction { } abstract protected static class BinaryOp extends TwoArgFunction { + @Override public LuaValue call(LuaValue x, LuaValue y) { return valueOf(call(x.checkdouble(), y.checkdouble())); } @@ -168,38 +171,47 @@ public class MathLib extends TwoArgFunction { } static final class abs extends UnaryOp { + @Override protected double call(double d) { return Math.abs(d); } } static final class ceil extends UnaryOp { + @Override protected double call(double d) { return Math.ceil(d); } } static final class cos extends UnaryOp { + @Override protected double call(double d) { return Math.cos(d); } } static final class deg extends UnaryOp { + @Override protected double call(double d) { return Math.toDegrees(d); } } static final class floor extends UnaryOp { + @Override protected double call(double d) { return Math.floor(d); } } static final class rad extends UnaryOp { + @Override protected double call(double d) { return Math.toRadians(d); } } static final class sin extends UnaryOp { + @Override protected double call(double d) { return Math.sin(d); } } static final class sqrt extends UnaryOp { + @Override protected double call(double d) { return Math.sqrt(d); } } static final class tan extends UnaryOp { + @Override protected double call(double d) { return Math.tan(d); } } @@ -210,12 +222,14 @@ public class MathLib extends TwoArgFunction { this.mathlib = mathlib; } + @Override protected double call(double d) { return mathlib.dpow_lib(Math.E, d); } } static final class fmod extends TwoArgFunction { + @Override public LuaValue call(LuaValue xv, LuaValue yv) { if (xv.islong() && yv.islong()) { return valueOf(xv.tolong()%yv.tolong()); @@ -225,31 +239,35 @@ public class MathLib extends TwoArgFunction { } static final class ldexp extends BinaryOp { + @Override protected double call(double x, double y) { // This is the behavior on os-x, windows differs in rounding behavior. - return x*Double.longBitsToDouble((((long) y)+1023)<<52); + return x*Double.longBitsToDouble((long) y+1023<<52); } } static final class pow extends BinaryOp { + @Override protected double call(double x, double y) { return MathLib.dpow_default(x, y); } } static class frexp extends VarArgFunction { + @Override public Varargs invoke(Varargs args) { double x = args.checkdouble(1); if (x == 0) return varargsOf(ZERO, ZERO); long bits = Double.doubleToLongBits(x); - double m = ((bits & (~(-1L<<52)))+(1L<<52))*((bits >= 0)? (.5/(1L<<52)): (-.5/(1L<<52))); - double e = (((int) (bits>>52)) & 0x7ff)-1022; + double m = ((bits & ~(-1L<<52))+(1L<<52))*(bits >= 0? .5/(1L<<52): -.5/(1L<<52)); + double e = ((int) (bits>>52) & 0x7ff)-1022; return varargsOf(valueOf(m), valueOf(e)); } } static class max extends VarArgFunction { + @Override public Varargs invoke(Varargs args) { LuaValue m = args.checkvalue(1); for (int i = 2, n = args.narg(); i <= n; ++i) { @@ -262,6 +280,7 @@ public class MathLib extends TwoArgFunction { } static class min extends VarArgFunction { + @Override public Varargs invoke(Varargs args) { LuaValue m = args.checkvalue(1); for (int i = 2, n = args.narg(); i <= n; ++i) { @@ -274,6 +293,7 @@ public class MathLib extends TwoArgFunction { } static class modf extends VarArgFunction { + @Override public Varargs invoke(Varargs args) { LuaValue n = args.arg1(); /* number is its own integer part, no fractional part */ @@ -281,7 +301,7 @@ public class MathLib extends TwoArgFunction { return varargsOf(n, valueOf(0.0)); double x = n.checkdouble(); /* integer part (rounds toward zero) */ - double intPart = (x > 0)? Math.floor(x): Math.ceil(x); + double intPart = x > 0? Math.floor(x): Math.ceil(x); /* fractional part (test needed for inf/-inf) */ double fracPart = x == intPart? 0.0: x-intPart; return varargsOf(valueOf(intPart), valueOf(fracPart)); @@ -291,10 +311,12 @@ public class MathLib extends TwoArgFunction { static class random extends LibFunction { Random random = new Random(); + @Override public LuaValue call() { return valueOf(random.nextDouble()); } + @Override public LuaValue call(LuaValue a) { int m = a.checkint(); if (m < 1) @@ -302,6 +324,7 @@ public class MathLib extends TwoArgFunction { return valueOf(1+random.nextInt(m)); } + @Override public LuaValue call(LuaValue a, LuaValue b) { int m = a.checkint(); int n = b.checkint(); @@ -319,6 +342,7 @@ public class MathLib extends TwoArgFunction { this.random = random; } + @Override public LuaValue call(LuaValue arg) { long seed = arg.checklong(); random.random = new Random(seed); diff --git a/luaj-core/src/main/java/org/luaj/vm2/lib/OneArgFunction.java b/luaj-core/src/main/java/org/luaj/vm2/lib/OneArgFunction.java index 8271ddfc..2a946761 100644 --- a/luaj-core/src/main/java/org/luaj/vm2/lib/OneArgFunction.java +++ b/luaj-core/src/main/java/org/luaj/vm2/lib/OneArgFunction.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 @@ -40,7 +40,7 @@ import org.luaj.vm2.Varargs; *

    * See {@link LibFunction} for more information on implementation libraries and * library functions. - * + * * @see #call(LuaValue) * @see LibFunction * @see ZeroArgFunction @@ -50,24 +50,29 @@ import org.luaj.vm2.Varargs; */ abstract public class OneArgFunction extends LibFunction { + @Override abstract public LuaValue call(LuaValue arg); /** Default constructor */ public OneArgFunction() { } + @Override public final LuaValue call() { return call(NIL); } + @Override public final LuaValue call(LuaValue arg1, LuaValue arg2) { return call(arg1); } + @Override public LuaValue call(LuaValue arg1, LuaValue arg2, LuaValue arg3) { return call(arg1); } + @Override public Varargs invoke(Varargs varargs) { return call(varargs.arg1()); } diff --git a/luaj-core/src/main/java/org/luaj/vm2/lib/OsLib.java b/luaj-core/src/main/java/org/luaj/vm2/lib/OsLib.java index 7666a307..53701016 100644 --- a/luaj-core/src/main/java/org/luaj/vm2/lib/OsLib.java +++ b/luaj-core/src/main/java/org/luaj/vm2/lib/OsLib.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 @@ -57,7 +57,7 @@ import org.luaj.vm2.Varargs; * Typically, this library is included as part of a call to either * {@link org.luaj.vm2.lib.jse.JsePlatform#standardGlobals()} or * {@link org.luaj.vm2.lib.jme.JmePlatform#standardGlobals()} - * + * *

      * {
      * 	@code
    @@ -65,14 +65,14 @@ import org.luaj.vm2.Varargs;
      * 	System.out.println(globals.get("os").get("time").call());
      * }
      * 
    - * + * * In this example the platform-specific {@link org.luaj.vm2.lib.jse.JseOsLib} * library will be loaded, which will include the base functionality provided by * this class. *

    * To instantiate and use it directly, link it into your globals table via * {@link LuaValue#load(LuaValue)} using code such as: - * + * *

      * {
      * 	@code
    @@ -84,7 +84,7 @@ import org.luaj.vm2.Varargs;
      * }
      * 
    *

    - * + * * @see LibFunction * @see org.luaj.vm2.lib.jse.JseOsLib * @see org.luaj.vm2.lib.jse.JsePlatform @@ -127,11 +127,12 @@ public class OsLib extends TwoArgFunction { * containing the library functions, adding that table to the supplied * environment, adding the table to package.loaded, and returning table as * the return value. - * + * * @param modname the module name supplied if this is loaded via 'require'. * @param env the environment to load into, typically a Globals * instance. */ + @Override public LuaValue call(LuaValue modname, LuaValue env) { globals = env.checkglobals(); LuaTable os = new LuaTable(); @@ -149,6 +150,7 @@ public class OsLib extends TwoArgFunction { this.name = name; } + @Override public Varargs invoke(Varargs args) { try { switch (opcode) { @@ -219,7 +221,7 @@ public class OsLib extends TwoArgFunction { /** * Returns the number of seconds from time t1 to time t2. In POSIX, Windows, * and some other systems, this value is exactly t2-t1. - * + * * @param t2 * @param t1 * @return diffeence in time values, in seconds @@ -232,14 +234,14 @@ public class OsLib extends TwoArgFunction { * If the time argument is present, this is the time to be formatted (see * the os.time function for a description of this value). Otherwise, date * formats the current time. - * + * * Date returns the date as a string, formatted according to the same rules * as ANSII strftime, but without support for %g, %G, or %V. - * + * * When called without arguments, date returns a reasonable date and time * representation that depends on the host system and on the current locale * (that is, os.date() is equivalent to os.date("%c")). - * + * * @param format * @param time time since epoch, or -1 if not supplied * @return a LString or a LTable containing date and time, formatted @@ -297,7 +299,7 @@ public class OsLib extends TwoArgFunction { result.append(String.valueOf(100+d.get(Calendar.HOUR_OF_DAY)).substring(1)); break; case 'I': - result.append(String.valueOf(100+(d.get(Calendar.HOUR_OF_DAY)%12)).substring(1)); + result.append(String.valueOf(100+d.get(Calendar.HOUR_OF_DAY)%12).substring(1)); break; case 'j': { // day of year. Calendar y0 = beginningOfYear(d); @@ -399,7 +401,7 @@ public class OsLib extends TwoArgFunction { * to be executed by an operating system shell. It returns a status code, * which is system-dependent. If command is absent, then it returns nonzero * if a shell is available and zero otherwise. - * + * * @param command command to pass to the system */ protected Varargs execute(String command) { @@ -409,7 +411,7 @@ public class OsLib extends TwoArgFunction { /** * Calls the C function exit, with an optional code, to terminate the host * program. - * + * * @param code */ protected void exit(int code) { @@ -420,16 +422,16 @@ public class OsLib extends TwoArgFunction { * Returns the value of the process environment variable varname, or the * System property value for varname, or null if the variable is not defined * in either environment. - * + * * The default implementation, which is used by the JmePlatform, only * queryies System.getProperty(). - * + * * The JsePlatform overrides this behavior and returns the environment * variable value using System.getenv() if it exists, or the System property * value if it does not. - * + * * A SecurityException may be thrown if access is not allowed for 'varname'. - * + * * @param varname * @return String value, or null if not defined */ @@ -440,7 +442,7 @@ public class OsLib extends TwoArgFunction { /** * Deletes the file or directory with the given name. Directories must be * empty to be removed. If this function fails, it throws and IOException - * + * * @param filename * @throws IOException if it fails */ @@ -451,7 +453,7 @@ public class OsLib extends TwoArgFunction { /** * Renames file or directory named oldname to newname. If this function * fails,it throws and IOException - * + * * @param oldname old file name * @param newname new file name * @throws IOException if it fails @@ -465,14 +467,14 @@ public class OsLib extends TwoArgFunction { * locale; category is an optional string describing which category to * change: "all", "collate", "ctype", "monetary", "numeric", or "time"; the * default category is "all". - * + * * If locale is the empty string, the current locale is set to an * implementation- defined native locale. If locale is the string "C", the * current locale is set to the standard C locale. - * + * * When called with null as the first argument, this function only returns * the name of the current locale for the given category. - * + * * @param locale * @param category * @return the name of the new locale, or null if the request cannot be @@ -488,7 +490,7 @@ public class OsLib extends TwoArgFunction { * must have fields year, month, and day, and may have fields hour, min, * sec, and isdst (for a description of these fields, see the os.date * function). - * + * * @param table * @return long value for the time */ @@ -514,18 +516,18 @@ public class OsLib extends TwoArgFunction { * Returns a string with a file name that can be used for a temporary file. * The file must be explicitly opened before its use and explicitly removed * when no longer needed. - * + * * On some systems (POSIX), this function also creates a file with that * name, to avoid security risks. (Someone else might create the file with * wrong permissions in the time between getting the name and creating the * file.) You still have to open the file to use it and to remove it (even * if you do not use it). - * + * * @return String filename to use */ protected String tmpname() { synchronized (OsLib.class) { - return TMP_PREFIX+(tmpnames++)+TMP_SUFFIX; + return TMP_PREFIX+tmpnames+++TMP_SUFFIX; } } } diff --git a/luaj-core/src/main/java/org/luaj/vm2/lib/PackageLib.java b/luaj-core/src/main/java/org/luaj/vm2/lib/PackageLib.java index e5450cf1..7fe704b7 100644 --- a/luaj-core/src/main/java/org/luaj/vm2/lib/PackageLib.java +++ b/luaj-core/src/main/java/org/luaj/vm2/lib/PackageLib.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,6 +22,7 @@ package org.luaj.vm2.lib; import java.io.InputStream; +import java.nio.file.FileSystems; import org.luaj.vm2.Globals; import org.luaj.vm2.LuaFunction; @@ -33,7 +34,7 @@ import org.luaj.vm2.Varargs; /** * Subclass of {@link LibFunction} which implements the lua standard package and * module library functions. - * + * *

    Lua Environment Variables

    The following variables are available to * lua scrips when this library has been loaded: *
      @@ -44,18 +45,18 @@ import org.luaj.vm2.Varargs; *
    • "package.searchers" Lua table of functions that search for * object to load. *
    - * + * *

    Java Environment Variables

    These Java environment variables affect * the library behavior: *
      *
    • "luaj.package.path" Initial value for * "package.path". Default value is "?.lua" *
    - * + * *

    Loading

    Typically, this library is included as part of a call to * either {@link org.luaj.vm2.lib.jse.JsePlatform#standardGlobals()} or * {@link org.luaj.vm2.lib.jme.JmePlatform#standardGlobals()} - * + * *
      *  {@code
      * Globals globals = JsePlatform.standardGlobals();
    @@ -65,7 +66,7 @@ import org.luaj.vm2.Varargs;
      * 

    * To instantiate and use it directly, link it into your globals table via * {@link LuaValue#load(LuaValue)} using code such as: - * + * *

      * {
      * 	@code
    @@ -75,14 +76,14 @@ import org.luaj.vm2.Varargs;
      * 	System.out.println(globals.get("require").call("foo"));
      * }
      * 
    - * + * *

    Limitations

    This library has been implemented to match as closely as * possible the behavior in the corresponding library in C. However, the default * filesystem search semantics are different and delegated to the bas library as * outlined in the {@link BaseLib} and {@link org.luaj.vm2.lib.jse.JseBaseLib} * documentation. *

    - * + * * @see LibFunction * @see BaseLib * @see org.luaj.vm2.lib.jse.JseBaseLib @@ -142,7 +143,7 @@ public class PackageLib extends TwoArgFunction { private static final LuaString _SENTINEL = valueOf("\u0001"); - private static final String FILE_SEP = System.getProperty("file.separator"); + private static final String FILE_SEP = FileSystems.getDefault().getSeparator(); public PackageLib() {} @@ -151,11 +152,12 @@ public class PackageLib extends TwoArgFunction { * functions to the supplied environment, and returning it as the return * value. It also creates the package.preload and package.loaded tables for * use by other libraries. - * + * * @param modname the module name supplied if this is loaded via 'require'. * @param env the environment to load into, typically a Globals * instance. */ + @Override public LuaValue call(LuaValue modname, LuaValue env) { globals = env.checkglobals(); globals.set("require", new require()); @@ -190,6 +192,7 @@ public class PackageLib extends TwoArgFunction { package_.set(_PATH, LuaValue.valueOf(newLuaPath)); } + @Override public String tojstring() { return "package"; } @@ -198,23 +201,23 @@ public class PackageLib extends TwoArgFunction { /** * require (modname) - * + * * Loads the given module. The function starts by looking into the * package.loaded table to determine whether modname is already loaded. If * it is, then require returns the value stored at package.loaded[modname]. * Otherwise, it tries to find a loader for the module. - * + * * To find a loader, require is guided by the package.searchers sequence. By * changing this sequence, we can change how require looks for a module. The * following explanation is based on the default configuration for * package.searchers. - * + * * First require queries package.preload[modname]. If it has a value, this * value (which should be a function) is the loader. Otherwise require * searches for a Lua loader using the path stored in package.path. If that * also fails, it searches for a Java loader using the classpath, using the * public default constructor, and casting the instance to LuaFunction. - * + * * Once a loader is found, require calls the loader with two arguments: * modname and an extra value dependent on how it got the loader. If the * loader came from a file, this extra value is the file name. If the loader @@ -224,11 +227,12 @@ public class PackageLib extends TwoArgFunction { * value and has not assigned any value to package.loaded[modname], then * require assigns true to this entry. In any case, require returns the * final value of package.loaded[modname]. - * + * * If there is any error loading or running the module, or if it cannot find * any loader for the module, then require raises an error. */ public class require extends OneArgFunction { + @Override public LuaValue call(LuaValue arg) { LuaString name = arg.checkstring(); LuaValue loaded = package_.get(_LOADED); @@ -269,6 +273,7 @@ public class PackageLib extends TwoArgFunction { } public static class loadlib extends VarArgFunction { + @Override public Varargs invoke(Varargs args) { args.checkstring(1); return varargsOf(NIL, valueOf("dynamic libraries not enabled"), valueOf("absent")); @@ -276,6 +281,7 @@ public class PackageLib extends TwoArgFunction { } public class preload_searcher extends VarArgFunction { + @Override public Varargs invoke(Varargs args) { LuaString name = args.checkstring(1); LuaValue val = package_.get(_PRELOAD).get(name); @@ -284,6 +290,7 @@ public class PackageLib extends TwoArgFunction { } public class lua_searcher extends VarArgFunction { + @Override public Varargs invoke(Varargs args) { LuaString name = args.checkstring(1); @@ -311,6 +318,7 @@ public class PackageLib extends TwoArgFunction { } public class searchpath extends VarArgFunction { + @Override public Varargs invoke(Varargs args) { String name = args.checkjstring(1); String path = args.checkjstring(2); @@ -358,6 +366,7 @@ public class PackageLib extends TwoArgFunction { } public class java_searcher extends VarArgFunction { + @Override public Varargs invoke(Varargs args) { String name = args.checkjstring(1); String classname = toClassname(name); @@ -385,11 +394,11 @@ public class PackageLib extends TwoArgFunction { j -= 4; for (int k = 0; k < j; k++) { char c = filename.charAt(k); - if ((!isClassnamePart(c)) || (c == '/') || (c == '\\')) { + if (!isClassnamePart(c) || c == '/' || c == '\\') { StringBuffer sb = new StringBuffer(j); for (int i = 0; i < j; i++) { c = filename.charAt(i); - sb.append((isClassnamePart(c))? c: ((c == '/') || (c == '\\'))? '.': '_'); + sb.append(isClassnamePart(c)? c: c == '/' || c == '\\'? '.': '_'); } return sb.toString(); } @@ -398,7 +407,7 @@ public class PackageLib extends TwoArgFunction { } private static final boolean isClassnamePart(char c) { - if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')) + if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9') return true; switch (c) { case '.': diff --git a/luaj-core/src/main/java/org/luaj/vm2/lib/ResourceFinder.java b/luaj-core/src/main/java/org/luaj/vm2/lib/ResourceFinder.java index f67c1b8b..af145f72 100644 --- a/luaj-core/src/main/java/org/luaj/vm2/lib/ResourceFinder.java +++ b/luaj-core/src/main/java/org/luaj/vm2/lib/ResourceFinder.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 @@ -38,7 +38,7 @@ import org.luaj.vm2.Globals; *

    * The io library does not use this API for file manipulation. *

    - * + * * @see BaseLib * @see Globals#finder * @see org.luaj.vm2.lib.jse.JseBaseLib @@ -49,12 +49,12 @@ public interface ResourceFinder { /** * Try to open a file, or return null if not found. - * + * * @see org.luaj.vm2.lib.BaseLib * @see org.luaj.vm2.lib.jse.JseBaseLib - * + * * @param filename * @return InputStream, or null if not found. */ - public InputStream findResource(String filename); + InputStream findResource(String filename); } diff --git a/luaj-core/src/main/java/org/luaj/vm2/lib/StringLib.java b/luaj-core/src/main/java/org/luaj/vm2/lib/StringLib.java index c49f741f..713ab9be 100644 --- a/luaj-core/src/main/java/org/luaj/vm2/lib/StringLib.java +++ b/luaj-core/src/main/java/org/luaj/vm2/lib/StringLib.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 @@ -39,7 +39,7 @@ import org.luaj.vm2.compiler.DumpState; * Typically, this library is included as part of a call to either * {@link org.luaj.vm2.lib.jse.JsePlatform#standardGlobals()} or * {@link org.luaj.vm2.lib.jme.JmePlatform#standardGlobals()} - * + * *

      * {
      * 	@code
    @@ -50,7 +50,7 @@ import org.luaj.vm2.compiler.DumpState;
      * 

    * To instantiate and use it directly, link it into your globals table via * {@link LuaValue#load(LuaValue)} using code such as: - * + * *

      * {
      * 	@code
    @@ -63,7 +63,7 @@ import org.luaj.vm2.compiler.DumpState;
      * 
    *

    * This is a direct port of the corresponding library in C. - * + * * @see LibFunction * @see org.luaj.vm2.lib.jse.JsePlatform * @see org.luaj.vm2.lib.jme.JmePlatform @@ -93,11 +93,12 @@ public class StringLib extends TwoArgFunction { * used in a server environment, sandboxing should be used. In particular, * the {@link LuaString#s_metatable} table should probably be made * read-only. - * + * * @param modname the module name supplied if this is loaded via 'require'. * @param env the environment to load into, typically a Globals * instance. */ + @Override public LuaValue call(LuaValue modname, LuaValue env) { LuaTable string = new LuaTable(); string.set("byte", new _byte()); @@ -126,15 +127,16 @@ public class StringLib extends TwoArgFunction { /** * string.byte (s [, i [, j]]) - * + * * Returns the internal numerical codes of the characters s[i], s[i+1], ..., * s[j]. The default value for i is 1; the default value for j is i. - * + * * Note that numerical codes are not necessarily portable across platforms. - * + * * @param args the calling args */ static final class _byte extends VarArgFunction { + @Override public Varargs invoke(Varargs args) { LuaString s = args.checkstring(1); int l = s.m_length; @@ -147,7 +149,7 @@ public class StringLib extends TwoArgFunction { pose = l; if (posi > pose) return NONE; /* empty interval; return no values */ - n = (int) (pose-posi+1); + n = pose-posi+1; if (posi+n <= pose) /* overflow? */ error("string slice too long"); LuaValue[] v = new LuaValue[n]; @@ -159,16 +161,17 @@ public class StringLib extends TwoArgFunction { /** * string.char (...) - * + * * Receives zero or more integers. Returns a string with length equal to the * number of arguments, in which each character has the internal numerical * code equal to its corresponding argument. - * + * * Note that numerical codes are not necessarily portable across platforms. - * + * * @param args the calling VM */ static final class _char extends VarArgFunction { + @Override public Varargs invoke(Varargs args) { int n = args.narg(); byte[] bytes = new byte[n]; @@ -184,16 +187,17 @@ public class StringLib extends TwoArgFunction { /** * string.dump (function[, stripDebug]) - * + * * Returns a string containing a binary representation of the given * function, so that a later loadstring on this string returns a copy of the * function. function must be a Lua function without upvalues. Boolean param * stripDebug - true to strip debugging info, false otherwise. The default * value for stripDebug is true. - * + * * TODO: port dumping code as optional add-on */ static final class dump extends VarArgFunction { + @Override public Varargs invoke(Varargs args) { LuaValue f = args.checkfunction(1); ByteArrayOutputStream baos = new ByteArrayOutputStream(); @@ -208,7 +212,7 @@ public class StringLib extends TwoArgFunction { /** * string.find (s, pattern [, init [, plain]]) - * + * * Looks for the first match of pattern in the string s. If it finds a * match, then find returns the indices of s where this occurrence starts * and ends; otherwise, it returns nil. A third, optional numerical argument @@ -217,11 +221,12 @@ public class StringLib extends TwoArgFunction { * off the pattern matching facilities, so the function does a plain "find * substring" operation, with no characters in pattern being considered * "magic". Note that if plain is given, then init must be given as well. - * + * * If the pattern has captures, then in a successful match the captured * values are also returned, after the two indices. */ static final class find extends VarArgFunction { + @Override public Varargs invoke(Varargs args) { return str_find_aux(args, true); } @@ -229,7 +234,7 @@ public class StringLib extends TwoArgFunction { /** * string.format (formatstring, ...) - * + * * Returns a formatted version of its variable number of arguments following * the description given in its first argument (which must be a string). The * format string follows the same rules as the printf family of standard C @@ -242,14 +247,15 @@ public class StringLib extends TwoArgFunction { * string.format('%q', 'a string with "quotes" and \n new line') * * will produce the string: "a string with \"quotes\" and \ new line" - * + * * The options c, d, E, e, f, g, G, i, o, u, X, and x all expect a number as * argument, whereas q and s expect a string. - * + * * This function does not accept string values containing embedded zeros, * except as arguments to the q option. */ final class format extends VarArgFunction { + @Override public Varargs invoke(Varargs args) { LuaString fmt = args.checkstring(1); final int n = fmt.length(); @@ -375,7 +381,7 @@ public class StringLib extends TwoArgFunction { boolean moreFlags = true; while ( moreFlags ) { - switch (c = ((p < n)? strfrmt.luaByte(p++): 0)) { + switch (c = p < n? strfrmt.luaByte(p++): 0) { case '-': leftAdjust = true; break; @@ -402,22 +408,22 @@ public class StringLib extends TwoArgFunction { width = -1; if (Character.isDigit((char) c)) { width = c-'0'; - c = ((p < n)? strfrmt.luaByte(p++): 0); + c = p < n? strfrmt.luaByte(p++): 0; if (Character.isDigit((char) c)) { - width = width*10+(c-'0'); - c = ((p < n)? strfrmt.luaByte(p++): 0); + width = width*10+c-'0'; + c = p < n? strfrmt.luaByte(p++): 0; } } precision = -1; if (c == '.') { - c = ((p < n)? strfrmt.luaByte(p++): 0); + c = p < n? strfrmt.luaByte(p++): 0; if (Character.isDigit((char) c)) { precision = c-'0'; - c = ((p < n)? strfrmt.luaByte(p++): 0); + c = p < n? strfrmt.luaByte(p++): 0; if (Character.isDigit((char) c)) { - precision = precision*10+(c-'0'); - c = ((p < n)? strfrmt.luaByte(p++): 0); + precision = precision*10+c-'0'; + c = p < n? strfrmt.luaByte(p++): 0; } } } @@ -527,14 +533,14 @@ public class StringLib extends TwoArgFunction { /** * string.gmatch (s, pattern) - * + * * Returns an iterator function that, each time it is called, returns the * next captures from pattern over string s. If pattern specifies no * captures, then the whole match is produced in each call. - * + * * As an example, the following loop s = "hello world from Lua" for w in * string.gmatch(s, "%a+") do print(w) end - * + * * will iterate over all the words from string s, printing one per line. The * next example collects all pairs key=value from the given string into a * table: t = {} s = "from=world, to=Lua" for k, v in string.gmatch(s, @@ -544,6 +550,7 @@ public class StringLib extends TwoArgFunction { * anchor, as this would prevent the iteration. */ static final class gmatch extends VarArgFunction { + @Override public Varargs invoke(Varargs args) { LuaString src = args.checkstring(1); LuaString pat = args.checkstring(2); @@ -564,6 +571,7 @@ public class StringLib extends TwoArgFunction { this.lastmatch = -1; } + @Override public Varargs invoke(Varargs args) { for (; soffset <= srclen; soffset++) { ms.reset(); @@ -584,30 +592,30 @@ public class StringLib extends TwoArgFunction { * replacement string specified by repl, which may be a string, a table, or * a function. gsub also returns, as its second value, the total number of * matches that occurred. - * + * * If repl is a string, then its value is used for replacement. The * character % works as an escape character: any sequence in repl of the * form %n, with n between 1 and 9, stands for the value of the n-th * captured substring (see below). The sequence %0 stands for the whole * match. The sequence %% stands for a single %. - * + * * If repl is a table, then the table is queried for every match, using the * first capture as the key; if the pattern specifies no captures, then the * whole match is used as the key. - * + * * If repl is a function, then this function is called every time a match * occurs, with all captured substrings passed as arguments, in order; if * the pattern specifies no captures, then the whole match is passed as a * sole argument. - * + * * If the value returned by the table query or by the function call is a * string or a number, then it is used as the replacement string; otherwise, * if it is false or nil, then there is no replacement (that is, the * original match is kept in the string). - * + * * Here are some examples: x = string.gsub("hello world", "(%w+)", "%1 %1") * --> x="hello hello world world" - * + * * x = string.gsub("hello world", "%w+", "%0 %0", 1) --> x="hello hello * world" * @@ -624,6 +632,7 @@ public class StringLib extends TwoArgFunction { * string.gsub("$name-$version.tar.gz", "%$(%w+)", t) --> x="lua-5.1.tar.gz" */ static final class gsub extends VarArgFunction { + @Override public Varargs invoke(Varargs args) { LuaString src = args.checkstring(1); final int srclen = src.length(); @@ -659,11 +668,12 @@ public class StringLib extends TwoArgFunction { /** * string.len (s) - * + * * Receives a string and returns its length. The empty string "" has length * 0. Embedded zeros are counted, so "a\000bc\000" has length 5. */ static final class len extends OneArgFunction { + @Override public LuaValue call(LuaValue arg) { return arg.checkstring().len(); } @@ -671,13 +681,14 @@ public class StringLib extends TwoArgFunction { /** * string.lower (s) - * + * * Receives a string and returns a copy of this string with all uppercase * letters changed to lowercase. All other characters are left unchanged. * The definition of what an uppercase letter is depends on the current * locale. */ static final class lower extends OneArgFunction { + @Override public LuaValue call(LuaValue arg) { return valueOf(arg.checkjstring().toLowerCase()); } @@ -685,7 +696,7 @@ public class StringLib extends TwoArgFunction { /** * string.match (s, pattern [, init]) - * + * * Looks for the first match of pattern in the string s. If it finds one, * then match returns the captures from the pattern; otherwise it returns * nil. If pattern specifies no captures, then the whole match is returned. @@ -693,6 +704,7 @@ public class StringLib extends TwoArgFunction { * search; its default value is 1 and may be negative. */ static final class match extends VarArgFunction { + @Override public Varargs invoke(Varargs args) { return str_find_aux(args, false); } @@ -700,10 +712,11 @@ public class StringLib extends TwoArgFunction { /** * string.rep (s, n) - * + * * Returns a string that is the concatenation of n copies of the string s. */ static final class rep extends VarArgFunction { + @Override public Varargs invoke(Varargs args) { LuaString s = args.checkstring(1); int n = args.checkint(2); @@ -718,10 +731,11 @@ public class StringLib extends TwoArgFunction { /** * string.reverse (s) - * + * * Returns a string that is the string s reversed. */ static final class reverse extends OneArgFunction { + @Override public LuaValue call(LuaValue arg) { LuaString s = arg.checkstring(); int n = s.length(); @@ -734,7 +748,7 @@ public class StringLib extends TwoArgFunction { /** * string.sub (s, i [, j]) - * + * * Returns the substring of s that starts at i and continues until j; i and * j may be negative. If j is absent, then it is assumed to be equal to -1 * (which is the same as the string length). In particular, the call @@ -742,6 +756,7 @@ public class StringLib extends TwoArgFunction { * -i) returns a suffix of s with length i. */ static final class sub extends VarArgFunction { + @Override public Varargs invoke(Varargs args) { final LuaString s = args.checkstring(1); final int l = s.length(); @@ -764,13 +779,14 @@ public class StringLib extends TwoArgFunction { /** * string.upper (s) - * + * * Receives a string and returns a copy of this string with all lowercase * letters changed to uppercase. All other characters are left unchanged. * The definition of what a lowercase letter is depends on the current * locale. */ static final class upper extends OneArgFunction { + @Override public LuaValue call(LuaValue arg) { return valueOf(arg.checkjstring().toUpperCase()); } @@ -824,7 +840,7 @@ public class StringLib extends TwoArgFunction { } static int posrelat(int pos, int len) { - return (pos >= 0)? pos: len+pos+1; + return pos >= 0? pos: len+pos+1; } // Pattern matching implementation @@ -856,11 +872,11 @@ public class StringLib extends TwoArgFunction { final char c = (char) i; CHAR_TABLE[i] = (byte) ((Character.isDigit(c)? MASK_DIGIT: 0) | (Character.isLowerCase(c)? MASK_LOWERCASE: 0) | (Character.isUpperCase(c)? MASK_UPPERCASE: 0) - | ((c < ' ' || c == 0x7F)? MASK_CONTROL: 0)); - if ((c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F') || (c >= '0' && c <= '9')) { + | (c < ' ' || c == 0x7F? MASK_CONTROL: 0)); + if (c >= 'a' && c <= 'f' || c >= 'A' && c <= 'F' || c >= '0' && c <= '9') { CHAR_TABLE[i] |= MASK_HEXDIGIT; } - if ((c >= '!' && c <= '/') || (c >= ':' && c <= '@') || (c >= '[' && c <= '`') || (c >= '{' && c <= '~')) { + if (c >= '!' && c <= '/' || c >= ':' && c <= '@' || c >= '[' && c <= '`' || c >= '{' && c <= '~') { CHAR_TABLE[i] |= MASK_PUNCT; } if ((CHAR_TABLE[i] & (MASK_LOWERCASE | MASK_UPPERCASE)) != 0) { @@ -874,7 +890,7 @@ public class StringLib extends TwoArgFunction { CHAR_TABLE['\t'] |= MASK_SPACE; CHAR_TABLE[0x0B /* '\v' */ ] |= MASK_SPACE; CHAR_TABLE['\f'] |= MASK_SPACE; - }; + } static class MatchState { int matchdepth; /* control for recursive depth (to avoid C stack overflow) */ @@ -905,7 +921,7 @@ public class StringLib extends TwoArgFunction { for (int i = 0; i < l; ++i) { byte b = (byte) news.luaByte(i); if (b != L_ESC) { - lbuf.append((byte) b); + lbuf.append(b); } else { ++i; // skip ESC b = (byte) (i < l? news.luaByte(i): 0); @@ -955,7 +971,7 @@ public class StringLib extends TwoArgFunction { } Varargs push_captures(boolean wholeMatch, int soff, int end) { - int nlevels = (this.level == 0 && wholeMatch)? 1: this.level; + int nlevels = this.level == 0 && wholeMatch? 1: this.level; switch (nlevels) { case 0: return NONE; @@ -1067,12 +1083,12 @@ public class StringLib extends TwoArgFunction { res = (cdata & MASK_HEXDIGIT) != 0; break; case 'z': - res = (c == 0); + res = c == 0; break; /* deprecated option */ default: return cl == c; } - return (lcl == cl)? res: !res; + return lcl == cl == res; } boolean matchbracketclass(int c, int poff, int ec) { @@ -1086,7 +1102,7 @@ public class StringLib extends TwoArgFunction { poff++; if (match_class(c, p.luaByte(poff))) return sig; - } else if ((p.luaByte(poff+1) == '-') && (poff+2 < ec)) { + } else if (p.luaByte(poff+1) == '-' && poff+2 < ec) { poff += 2; if (p.luaByte(poff-2) <= c && c <= p.luaByte(poff)) return sig; @@ -1147,8 +1163,8 @@ public class StringLib extends TwoArgFunction { error("missing '[' after '%f' in pattern"); } int ep = classend(poffset); - int previous = (soffset == 0)? '\0': s.luaByte(soffset-1); - int next = (soffset == s.length())? '\0': s.luaByte(soffset); + int previous = soffset == 0? '\0': s.luaByte(soffset-1); + int next = soffset == s.length()? '\0': s.luaByte(soffset); if (matchbracketclass(previous, poffset, ep-1) || !matchbracketclass(next, poffset, ep-1)) return -1; poffset = ep; @@ -1166,23 +1182,23 @@ public class StringLib extends TwoArgFunction { } case '$': if (poffset+1 == p.length()) - return (soffset == s.length())? soffset: -1; + return soffset == s.length()? soffset: -1; } int ep = classend(poffset); boolean m = soffset < s.length() && singlematch(s.luaByte(soffset), poffset, ep); - int pc = (ep < p.length())? p.luaByte(ep): '\0'; + int pc = ep < p.length()? p.luaByte(ep): '\0'; switch (pc) { case '?': int res; - if (m && ((res = match(soffset+1, ep+1)) != -1)) + if (m && (res = match(soffset+1, ep+1)) != -1) return res; poffset = ep+1; continue; case '*': return max_expand(soffset, poffset, ep); case '+': - return (m? max_expand(soffset+1, poffset, ep): -1); + return m? max_expand(soffset+1, poffset, ep): -1; case '-': return min_expand(soffset, poffset, ep); default: @@ -1190,7 +1206,6 @@ public class StringLib extends TwoArgFunction { return -1; soffset++; poffset = ep; - continue; } } } finally { @@ -1249,7 +1264,7 @@ public class StringLib extends TwoArgFunction { int match_capture(int soff, int l) { l = check_capture(l); int len = clen[l]; - if ((s.length()-soff) >= len && LuaString.equals(s, cinit[l], s, soff, len)) + if (s.length()-soff >= len && LuaString.equals(s, cinit[l], s, soff, len)) return soff+len; else return -1; diff --git a/luaj-core/src/main/java/org/luaj/vm2/lib/TableLib.java b/luaj-core/src/main/java/org/luaj/vm2/lib/TableLib.java index 0472dfed..3c5cc258 100644 --- a/luaj-core/src/main/java/org/luaj/vm2/lib/TableLib.java +++ b/luaj-core/src/main/java/org/luaj/vm2/lib/TableLib.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 @@ -28,12 +28,12 @@ import org.luaj.vm2.Varargs; /** * Subclass of {@link LibFunction} which implements the lua standard * {@code table} library. - * + * *

    * Typically, this library is included as part of a call to either * {@link org.luaj.vm2.lib.jse.JsePlatform#standardGlobals()} or * {@link org.luaj.vm2.lib.jme.JmePlatform#standardGlobals()} - * + * *

      * {
      * 	@code
    @@ -44,7 +44,7 @@ import org.luaj.vm2.Varargs;
      * 

    * To instantiate and use it directly, link it into your globals table via * {@link LuaValue#load(LuaValue)} using code such as: - * + * *

      * {
      * 	@code
    @@ -58,7 +58,7 @@ import org.luaj.vm2.Varargs;
      * 

    * This has been implemented to match as closely as possible the behavior in the * corresponding library in C. - * + * * @see LibFunction * @see org.luaj.vm2.lib.jse.JsePlatform * @see org.luaj.vm2.lib.jme.JmePlatform @@ -72,11 +72,12 @@ public class TableLib extends TwoArgFunction { * containing the library functions, adding that table to the supplied * environment, adding the table to package.loaded, and returning table as * the return value. - * + * * @param modname the module name supplied if this is loaded via 'require'. * @param env the environment to load into, typically a Globals * instance. */ + @Override public LuaValue call(LuaValue modname, LuaValue env) { LuaTable table = new LuaTable(); table.set("concat", new concat()); @@ -93,18 +94,22 @@ public class TableLib extends TwoArgFunction { // "concat" (table [, sep [, i [, j]]]) -> string static class concat extends TableLibFunction { + @Override public LuaValue call(LuaValue list) { return list.checktable().concat(EMPTYSTRING, 1, list.length()); } + @Override public LuaValue call(LuaValue list, LuaValue sep) { return list.checktable().concat(sep.checkstring(), 1, list.length()); } + @Override public LuaValue call(LuaValue list, LuaValue sep, LuaValue i) { return list.checktable().concat(sep.checkstring(), i.checkint(), list.length()); } + @Override public LuaValue call(LuaValue list, LuaValue sep, LuaValue i, LuaValue j) { return list.checktable().concat(sep.checkstring(), i.checkint(), j.checkint()); } @@ -112,6 +117,7 @@ public class TableLib extends TwoArgFunction { // "insert" (table, [pos,] value) static class insert extends VarArgFunction { + @Override public Varargs invoke(Varargs args) { switch (args.narg()) { case 2: { @@ -137,6 +143,7 @@ public class TableLib extends TwoArgFunction { // "pack" (...) -> table static class pack extends VarArgFunction { + @Override public Varargs invoke(Varargs args) { LuaValue t = tableOf(args, 1); t.set("n", args.narg()); @@ -146,6 +153,7 @@ public class TableLib extends TwoArgFunction { // "remove" (table [, pos]) -> removed-ele static class remove extends VarArgFunction { + @Override public Varargs invoke(Varargs args) { LuaTable table = args.checktable(1); int size = table.length(); @@ -159,6 +167,7 @@ public class TableLib extends TwoArgFunction { // "sort" (table [, comp]) static class sort extends VarArgFunction { + @Override public Varargs invoke(Varargs args) { args.checktable(1).sort(args.isnil(2)? NIL: args.checkfunction(2)); return NONE; @@ -167,6 +176,7 @@ public class TableLib extends TwoArgFunction { // "unpack", // (list [,i [,j]]) -> result1, ... static class unpack extends VarArgFunction { + @Override public Varargs invoke(Varargs args) { LuaTable t = args.checktable(1); // do not waste resource for calc rawlen if arg3 is not nil diff --git a/luaj-core/src/main/java/org/luaj/vm2/lib/TableLibFunction.java b/luaj-core/src/main/java/org/luaj/vm2/lib/TableLibFunction.java index 5fabef7e..f9286b0a 100644 --- a/luaj-core/src/main/java/org/luaj/vm2/lib/TableLibFunction.java +++ b/luaj-core/src/main/java/org/luaj/vm2/lib/TableLibFunction.java @@ -3,6 +3,7 @@ package org.luaj.vm2.lib; import org.luaj.vm2.LuaValue; class TableLibFunction extends LibFunction { + @Override public LuaValue call() { return argerror(1, "table expected, got no value"); } diff --git a/luaj-core/src/main/java/org/luaj/vm2/lib/ThreeArgFunction.java b/luaj-core/src/main/java/org/luaj/vm2/lib/ThreeArgFunction.java index dcb72db8..05a6b3a1 100644 --- a/luaj-core/src/main/java/org/luaj/vm2/lib/ThreeArgFunction.java +++ b/luaj-core/src/main/java/org/luaj/vm2/lib/ThreeArgFunction.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 @@ -41,7 +41,7 @@ import org.luaj.vm2.Varargs; *

    * See {@link LibFunction} for more information on implementation libraries and * library functions. - * + * * @see #call(LuaValue,LuaValue,LuaValue) * @see LibFunction * @see ZeroArgFunction @@ -51,24 +51,29 @@ import org.luaj.vm2.Varargs; */ abstract public class ThreeArgFunction extends LibFunction { + @Override abstract public LuaValue call(LuaValue arg1, LuaValue arg2, LuaValue arg3); /** Default constructor */ public ThreeArgFunction() { } + @Override public final LuaValue call() { return call(NIL, NIL, NIL); } + @Override public final LuaValue call(LuaValue arg) { return call(arg, NIL, NIL); } + @Override public LuaValue call(LuaValue arg1, LuaValue arg2) { return call(arg1, arg2, NIL); } + @Override public Varargs invoke(Varargs varargs) { return call(varargs.arg1(), varargs.arg(2), varargs.arg(3)); } diff --git a/luaj-core/src/main/java/org/luaj/vm2/lib/TwoArgFunction.java b/luaj-core/src/main/java/org/luaj/vm2/lib/TwoArgFunction.java index 7309946b..f7ef431d 100644 --- a/luaj-core/src/main/java/org/luaj/vm2/lib/TwoArgFunction.java +++ b/luaj-core/src/main/java/org/luaj/vm2/lib/TwoArgFunction.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 @@ -41,7 +41,7 @@ import org.luaj.vm2.Varargs; *

    * See {@link LibFunction} for more information on implementation libraries and * library functions. - * + * * @see #call(LuaValue,LuaValue) * @see LibFunction * @see ZeroArgFunction @@ -51,24 +51,29 @@ import org.luaj.vm2.Varargs; */ abstract public class TwoArgFunction extends LibFunction { + @Override abstract public LuaValue call(LuaValue arg1, LuaValue arg2); /** Default constructor */ public TwoArgFunction() { } + @Override public final LuaValue call() { return call(NIL, NIL); } + @Override public final LuaValue call(LuaValue arg) { return call(arg, NIL); } + @Override public LuaValue call(LuaValue arg1, LuaValue arg2, LuaValue arg3) { return call(arg1, arg2); } + @Override public Varargs invoke(Varargs varargs) { return call(varargs.arg1(), varargs.arg(2)); } diff --git a/luaj-core/src/main/java/org/luaj/vm2/lib/VarArgFunction.java b/luaj-core/src/main/java/org/luaj/vm2/lib/VarArgFunction.java index 8fc7a743..e286bdd2 100644 --- a/luaj-core/src/main/java/org/luaj/vm2/lib/VarArgFunction.java +++ b/luaj-core/src/main/java/org/luaj/vm2/lib/VarArgFunction.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 @@ -40,7 +40,7 @@ import org.luaj.vm2.Varargs; *

    * See {@link LibFunction} for more information on implementation libraries and * library functions. - * + * * @see #invoke(Varargs) * @see LibFunction * @see ZeroArgFunction @@ -53,18 +53,22 @@ abstract public class VarArgFunction extends LibFunction { public VarArgFunction() { } + @Override public LuaValue call() { return invoke(NONE).arg1(); } + @Override public LuaValue call(LuaValue arg) { return invoke(arg).arg1(); } + @Override public LuaValue call(LuaValue arg1, LuaValue arg2) { return invoke(varargsOf(arg1, arg2)).arg1(); } + @Override public LuaValue call(LuaValue arg1, LuaValue arg2, LuaValue arg3) { return invoke(varargsOf(arg1, arg2, arg3)).arg1(); } @@ -73,13 +77,15 @@ abstract public class VarArgFunction extends LibFunction { * Subclass responsibility. May not have expected behavior for tail calls. * Should not be used if: - function has a possibility of returning a * TailcallVarargs - * + * * @param args the arguments to the function call. */ + @Override public Varargs invoke(Varargs args) { return onInvoke(args).eval(); } + @Override public Varargs onInvoke(Varargs args) { return invoke(args); } diff --git a/luaj-core/src/main/java/org/luaj/vm2/lib/ZeroArgFunction.java b/luaj-core/src/main/java/org/luaj/vm2/lib/ZeroArgFunction.java index d40f4f6e..9841a869 100644 --- a/luaj-core/src/main/java/org/luaj/vm2/lib/ZeroArgFunction.java +++ b/luaj-core/src/main/java/org/luaj/vm2/lib/ZeroArgFunction.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 @@ -38,7 +38,7 @@ import org.luaj.vm2.Varargs; *

    * See {@link LibFunction} for more information on implementation libraries and * library functions. - * + * * @see #call() * @see LibFunction * @see OneArgFunction @@ -48,24 +48,29 @@ import org.luaj.vm2.Varargs; */ abstract public class ZeroArgFunction extends LibFunction { + @Override abstract public LuaValue call(); /** Default constructor */ public ZeroArgFunction() { } + @Override public LuaValue call(LuaValue arg) { return call(); } + @Override public LuaValue call(LuaValue arg1, LuaValue arg2) { return call(); } + @Override public LuaValue call(LuaValue arg1, LuaValue arg2, LuaValue arg3) { return call(); } + @Override public Varargs invoke(Varargs varargs) { return call(); } diff --git a/luaj-jme/src/main/java/org/luaj/vm2/lib/jme/JmeIoLib.java b/luaj-jme/src/main/java/org/luaj/vm2/lib/jme/JmeIoLib.java index c0b41e8a..b8d11998 100644 --- a/luaj-jme/src/main/java/org/luaj/vm2/lib/jme/JmeIoLib.java +++ b/luaj-jme/src/main/java/org/luaj/vm2/lib/jme/JmeIoLib.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 @@ -43,7 +43,7 @@ import org.luaj.vm2.lib.LibFunction; *

    * Typically, this library is included as part of a call to * {@link org.luaj.vm2.lib.jme.JmePlatform#standardGlobals()} - * + * *

      * {
      * 	@code
    @@ -55,7 +55,7 @@ import org.luaj.vm2.lib.LibFunction;
      * For special cases where the smallest possible footprint is desired, a minimal
      * set of libraries could be loaded directly via {@link Globals#load(LuaValue)}
      * using code such as:
    - * 
    + *
      * 
      * {
      * 	@code
    @@ -72,7 +72,7 @@ import org.luaj.vm2.lib.LibFunction;
      * 

    * This has been implemented to match as closely as possible the behavior in the * corresponding library in C. - * + * * @see LibFunction * @see org.luaj.vm2.lib.jse.JsePlatform * @see org.luaj.vm2.lib.jme.JmePlatform @@ -83,25 +83,28 @@ import org.luaj.vm2.lib.LibFunction; */ public class JmeIoLib extends IoLib { + @Override protected File wrapStdin() throws IOException { return new FileImpl(globals.STDIN); } + @Override protected File wrapStdout() throws IOException { return new FileImpl(globals.STDOUT); } + @Override protected File wrapStderr() throws IOException { return new FileImpl(globals.STDERR); } + @Override protected File openFile(String filename, boolean readMode, boolean appendMode, boolean updateMode, boolean binaryMode) throws IOException { String url = "file:///" + filename; int mode = readMode? Connector.READ: Connector.READ_WRITE; StreamConnection conn = (StreamConnection) Connector.open(url, mode); - File f = readMode? new FileImpl(conn, conn.openInputStream(), null) - : new FileImpl(conn, conn.openInputStream(), conn.openOutputStream()); + /* if ( appendMode ) { f.seek("end",0); @@ -110,18 +113,21 @@ public class JmeIoLib extends IoLib { conn.truncate(0); } */ - return f; + return readMode? new FileImpl(conn, conn.openInputStream(), null) + : new FileImpl(conn, conn.openInputStream(), conn.openOutputStream()); } private static void notimplemented() throws IOException { throw new IOException("not implemented"); } + @Override protected File openProgram(String prog, String mode) throws IOException { notimplemented(); return null; } + @Override protected File tmpFile() throws IOException { notimplemented(); return null; @@ -149,14 +155,17 @@ public class JmeIoLib extends IoLib { this(null, null, o); } + @Override public String tojstring() { return "file (" + this.hashCode() + ")"; } + @Override public boolean isstdfile() { return conn == null; } + @Override public void close() throws IOException { closed = true; if (conn != null) { @@ -164,11 +173,13 @@ public class JmeIoLib extends IoLib { } } + @Override public void flush() throws IOException { if (os != null) os.flush(); } + @Override public void write(LuaString s) throws IOException { if (os != null) os.write(s.m_bytes, s.m_offset, s.m_length); @@ -178,10 +189,12 @@ public class JmeIoLib extends IoLib { flush(); } + @Override public boolean isclosed() { return closed; } + @Override public int seek(String option, int pos) throws IOException { /* if ( conn != null ) { @@ -201,23 +214,27 @@ public class JmeIoLib extends IoLib { return 0; } + @Override public void setvbuf(String mode, int size) { nobuffer = "no".equals(mode); } // get length remaining to read + @Override public int remaining() throws IOException { return -1; } // peek ahead one character + @Override public int peek() throws IOException { if (lookahead < 0) lookahead = is.read(); return lookahead; } - // return char if read, -1 if eof, throw IOException on other exception + // return char if read, -1 if eof, throw IOException on other exception + @Override public int read() throws IOException { if (lookahead >= 0) { int c = lookahead; @@ -231,6 +248,7 @@ public class JmeIoLib extends IoLib { } // return number of bytes read if positive, -1 if eof, throws IOException + @Override public int read(byte[] bytes, int offset, int length) throws IOException { int n, i = 0; if (is != null) { @@ -242,7 +260,7 @@ public class JmeIoLib extends IoLib { for (; i < length;) { n = is.read(bytes, offset+i, length-i); if (n < 0) - return (i > 0? i: -1); + return i > 0? i: -1; i += n; } } else { diff --git a/luaj-jme/src/main/java/org/luaj/vm2/lib/jme/JmePlatform.java b/luaj-jme/src/main/java/org/luaj/vm2/lib/jme/JmePlatform.java index d9614f49..9b30e276 100644 --- a/luaj-jme/src/main/java/org/luaj/vm2/lib/jme/JmePlatform.java +++ b/luaj-jme/src/main/java/org/luaj/vm2/lib/jme/JmePlatform.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 @@ -23,8 +23,6 @@ package org.luaj.vm2.lib.jme; import org.luaj.vm2.Globals; import org.luaj.vm2.LoadState; -import org.luaj.vm2.LuaThread; -import org.luaj.vm2.LuaValue; import org.luaj.vm2.compiler.LuaC; import org.luaj.vm2.lib.BaseLib; import org.luaj.vm2.lib.Bit32Lib; @@ -60,7 +58,7 @@ import org.luaj.vm2.lib.TableLib; * {@link #standardGlobals()} or debug globals using {@link #debugGlobals()} *

    * A simple example of initializing globals and using them from Java is: - * + * *

      * {
      * 	@code
    @@ -70,7 +68,7 @@ import org.luaj.vm2.lib.TableLib;
      * 
    *

    * Once globals are created, a simple way to load and run a script is: - * + * *

      *  {@code
      * LoadState.load( getClass().getResourceAsStream("main.lua"), "main.lua", globals ).call();
    @@ -78,13 +76,13 @@ import org.luaj.vm2.lib.TableLib;
      * 
    *

    * although {@code require} could also be used: - * + * *

      *  {@code
      * globals.get("require").call(LuaValue.valueOf("main"));
      * }
      * 
    - * + * * For this to succeed, the file "main.lua" must be a resource in the class * path. See {@link BaseLib} for details on finding scripts using * {@link ResourceFinder}. @@ -111,7 +109,7 @@ import org.luaj.vm2.lib.TableLib; *

    *

    * The class ensures that initialization is done in the correct order. - * + * * @see Globals * @see org.luaj.vm2.lib.jse.JsePlatform */ @@ -119,7 +117,7 @@ public class JmePlatform { /** * Create a standard set of globals for JME including all the libraries. - * + * * @return Table of globals initialized with the standard JME libraries * @see #debugGlobals() * @see org.luaj.vm2.lib.jse.JsePlatform @@ -143,7 +141,7 @@ public class JmePlatform { /** * Create standard globals including the {@link DebugLib} library. - * + * * @return Table of globals initialized with the standard JSE and debug * libraries * @see #standardGlobals() diff --git a/luaj-jse/src/main/java/lua.java b/luaj-jse/src/main/java/lua.java index 073bdf07..1961a951 100644 --- a/luaj-jse/src/main/java/lua.java +++ b/luaj-jse/src/main/java/lua.java @@ -11,7 +11,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 @@ -65,7 +65,7 @@ public class lua { public static void main(String[] args) throws IOException { // process args - boolean interactive = (args.length == 0); + boolean interactive = args.length == 0; boolean versioninfo = false; boolean processing = true; boolean nodebug = false; diff --git a/luaj-jse/src/main/java/luac.java b/luaj-jse/src/main/java/luac.java index 3331f62d..43122dfb 100644 --- a/luaj-jse/src/main/java/luac.java +++ b/luaj-jse/src/main/java/luac.java @@ -11,7 +11,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 @@ -128,10 +128,8 @@ public class luac { System.out.println(version); // open output file - OutputStream fos = new FileOutputStream(output); - // process input files - try { + try (OutputStream fos = new FileOutputStream(output)) { Globals globals = JsePlatform.standardGlobals(); processing = true; for (int i = 0; i < args.length; i++) { @@ -152,8 +150,6 @@ public class luac { } } } - } finally { - fos.close(); } } catch (IOException ioe) { diff --git a/luaj-jse/src/main/java/luajc.java b/luaj-jse/src/main/java/luajc.java index d6a2e4e8..1c819d0a 100644 --- a/luaj-jse/src/main/java/luajc.java +++ b/luaj-jse/src/main/java/luajc.java @@ -11,7 +11,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 @@ -55,16 +55,16 @@ public class luajc { System.exit(-1); } - private String srcdir = "."; - private String destdir = "."; - private boolean genmain = false; - private boolean recurse = false; - private boolean verbose = false; - private boolean loadclasses = false; - private String encoding = null; - private String pkgprefix = null; - private List files = new ArrayList(); - private Globals globals; + private String srcdir = "."; + private String destdir = "."; + private boolean genmain = false; + private boolean recurse = false; + private boolean verbose = false; + private boolean loadclasses = false; + private String encoding = null; + private String pkgprefix = null; + private final List files = new ArrayList(); + private final Globals globals; public static void main(String[] args) throws IOException { new luajc(args); @@ -136,8 +136,8 @@ public class luajc { } // collect up files to process - for (int i = 0; i < seeds.size(); i++) - collectFiles(srcdir + "/" + seeds.get(i)); + for (Object seed : seeds) + collectFiles(srcdir + "/" + seed); // check for at least one file if (files.size() <= 0) { @@ -147,8 +147,8 @@ public class luajc { // process input files globals = JsePlatform.standardGlobals(); - for (int i = 0, n = files.size(); i < n; i++) - processFile((InputFile) files.get(i)); + for (Object file : files) + processFile((InputFile) file); } private void collectFiles(String path) { @@ -164,14 +164,14 @@ public class luajc { private void scandir(File dir, String javapackage) { File[] f = dir.listFiles(); - for (int i = 0; i < f.length; i++) - scanfile(dir, f[i], javapackage); + for (File element : f) + scanfile(dir, element, javapackage); } private void scanfile(File dir, File f, String javapackage) { if (f.exists()) { if (f.isDirectory() && recurse) - scandir(f, (javapackage != null? javapackage + "." + f.getName(): f.getName())); + scandir(f, javapackage != null? javapackage + "." + f.getName(): f.getName()); else if (f.isFile() && f.getName().endsWith(".lua")) files.add(new InputFile(dir, f, javapackage)); } @@ -184,6 +184,7 @@ public class luajc { this.t = t; } + @Override public Class findClass(String classname) throws ClassNotFoundException { byte[] bytes = (byte[]) t.get(classname); if (bytes != null) diff --git a/luaj-jse/src/main/java/org/luaj/vm2/ast/Block.java b/luaj-jse/src/main/java/org/luaj/vm2/ast/Block.java index dbd86de4..af0b4383 100644 --- a/luaj-jse/src/main/java/org/luaj/vm2/ast/Block.java +++ b/luaj-jse/src/main/java/org/luaj/vm2/ast/Block.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,7 +26,7 @@ import java.util.List; public class Block extends Stat { - public List stats = new ArrayList(); + public List stats = new ArrayList<>(); public NameScope scope; public void add(Stat s) { @@ -35,6 +35,7 @@ public class Block extends Stat { stats.add(s); } + @Override public void accept(Visitor visitor) { visitor.visit(this); } diff --git a/luaj-jse/src/main/java/org/luaj/vm2/ast/Chunk.java b/luaj-jse/src/main/java/org/luaj/vm2/ast/Chunk.java index 958078b3..0e584a6d 100644 --- a/luaj-jse/src/main/java/org/luaj/vm2/ast/Chunk.java +++ b/luaj-jse/src/main/java/org/luaj/vm2/ast/Chunk.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 diff --git a/luaj-jse/src/main/java/org/luaj/vm2/ast/Exp.java b/luaj-jse/src/main/java/org/luaj/vm2/ast/Exp.java index c46083f8..4908b32f 100644 --- a/luaj-jse/src/main/java/org/luaj/vm2/ast/Exp.java +++ b/luaj-jse/src/main/java/org/luaj/vm2/ast/Exp.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 @@ -62,12 +62,12 @@ abstract public class Exp extends SyntaxElement { // TODO: constant folding if (lhs instanceof BinopExp) { BinopExp b = (BinopExp) lhs; - if ((precedence(op) > precedence(b.op)) || ((precedence(op) == precedence(b.op)) && isrightassoc(op))) + if (precedence(op) > precedence(b.op) || precedence(op) == precedence(b.op) && isrightassoc(op)) return binaryexp(b.lhs, b.op, binaryexp(b.rhs, op, rhs)); } if (rhs instanceof BinopExp) { BinopExp b = (BinopExp) rhs; - if ((precedence(op) > precedence(b.op)) || ((precedence(op) == precedence(b.op)) && !isrightassoc(op))) + if (precedence(op) > precedence(b.op) || precedence(op) == precedence(b.op) && !isrightassoc(op)) return binaryexp(binaryexp(lhs, op, b.lhs), b.op, b.rhs); } return new BinopExp(lhs, op, rhs); @@ -163,16 +163,19 @@ abstract public class Exp extends SyntaxElement { } abstract public static class PrimaryExp extends Exp { + @Override public boolean isvarexp() { return false; } + @Override public boolean isfunccall() { return false; } } abstract public static class VarExp extends PrimaryExp { + @Override public boolean isvarexp() { return true; } @@ -188,10 +191,12 @@ abstract public class Exp extends SyntaxElement { this.name = new Name(name); } + @Override public void markHasAssignment() { name.variable.hasassignments = true; } + @Override public void accept(Visitor visitor) { visitor.visit(this); } @@ -204,6 +209,7 @@ abstract public class Exp extends SyntaxElement { this.exp = exp; } + @Override public void accept(Visitor visitor) { visitor.visit(this); } @@ -218,6 +224,7 @@ abstract public class Exp extends SyntaxElement { this.name = new Name(name); } + @Override public void accept(Visitor visitor) { visitor.visit(this); } @@ -232,6 +239,7 @@ abstract public class Exp extends SyntaxElement { this.exp = exp; } + @Override public void accept(Visitor visitor) { visitor.visit(this); } @@ -246,14 +254,17 @@ abstract public class Exp extends SyntaxElement { this.args = args; } + @Override public boolean isfunccall() { return true; } + @Override public void accept(Visitor visitor) { visitor.visit(this); } + @Override public boolean isvarargexp() { return true; } @@ -267,10 +278,12 @@ abstract public class Exp extends SyntaxElement { this.name = new String(name); } + @Override public boolean isfunccall() { return true; } + @Override public void accept(Visitor visitor) { visitor.visit(this); } @@ -283,6 +296,7 @@ abstract public class Exp extends SyntaxElement { this.value = value; } + @Override public void accept(Visitor visitor) { visitor.visit(this); } @@ -290,10 +304,12 @@ abstract public class Exp extends SyntaxElement { public static class VarargsExp extends Exp { + @Override public void accept(Visitor visitor) { visitor.visit(this); } + @Override public boolean isvarargexp() { return true; } @@ -308,6 +324,7 @@ abstract public class Exp extends SyntaxElement { this.rhs = rhs; } + @Override public void accept(Visitor visitor) { visitor.visit(this); } @@ -323,6 +340,7 @@ abstract public class Exp extends SyntaxElement { this.rhs = rhs; } + @Override public void accept(Visitor visitor) { visitor.visit(this); } @@ -335,6 +353,7 @@ abstract public class Exp extends SyntaxElement { this.body = funcbody; } + @Override public void accept(Visitor visitor) { visitor.visit(this); } diff --git a/luaj-jse/src/main/java/org/luaj/vm2/ast/FuncArgs.java b/luaj-jse/src/main/java/org/luaj/vm2/ast/FuncArgs.java index 3152c6be..56768a15 100644 --- a/luaj-jse/src/main/java/org/luaj/vm2/ast/FuncArgs.java +++ b/luaj-jse/src/main/java/org/luaj/vm2/ast/FuncArgs.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 @@ -50,12 +50,12 @@ public class FuncArgs extends SyntaxElement { } public FuncArgs(LuaString string) { - this.exps = new ArrayList(); + this.exps = new ArrayList<>(); this.exps.add(Exp.constant(string)); } public FuncArgs(TableConstructor table) { - this.exps = new ArrayList(); + this.exps = new ArrayList<>(); this.exps.add(table); } diff --git a/luaj-jse/src/main/java/org/luaj/vm2/ast/FuncBody.java b/luaj-jse/src/main/java/org/luaj/vm2/ast/FuncBody.java index 30ab12bb..8b4f2335 100644 --- a/luaj-jse/src/main/java/org/luaj/vm2/ast/FuncBody.java +++ b/luaj-jse/src/main/java/org/luaj/vm2/ast/FuncBody.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 diff --git a/luaj-jse/src/main/java/org/luaj/vm2/ast/FuncName.java b/luaj-jse/src/main/java/org/luaj/vm2/ast/FuncName.java index d1146425..1aaba111 100644 --- a/luaj-jse/src/main/java/org/luaj/vm2/ast/FuncName.java +++ b/luaj-jse/src/main/java/org/luaj/vm2/ast/FuncName.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 @@ -42,7 +42,7 @@ public class FuncName extends SyntaxElement { public void adddot(String dot) { if (dots == null) - dots = new ArrayList(); + dots = new ArrayList<>(); dots.add(dot); } diff --git a/luaj-jse/src/main/java/org/luaj/vm2/ast/Name.java b/luaj-jse/src/main/java/org/luaj/vm2/ast/Name.java index 44507069..b24d6461 100644 --- a/luaj-jse/src/main/java/org/luaj/vm2/ast/Name.java +++ b/luaj-jse/src/main/java/org/luaj/vm2/ast/Name.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 diff --git a/luaj-jse/src/main/java/org/luaj/vm2/ast/NameResolver.java b/luaj-jse/src/main/java/org/luaj/vm2/ast/NameResolver.java index 6abd46a9..aef1e663 100644 --- a/luaj-jse/src/main/java/org/luaj/vm2/ast/NameResolver.java +++ b/luaj-jse/src/main/java/org/luaj/vm2/ast/NameResolver.java @@ -30,9 +30,11 @@ public class NameResolver extends Visitor { scope = scope.outerScope; } + @Override public void visit(NameScope scope) { } + @Override public void visit(Block block) { pushScope(); block.scope = scope; @@ -40,6 +42,7 @@ public class NameResolver extends Visitor { popScope(); } + @Override public void visit(FuncBody body) { pushScope(); scope.functionNestingCount++; @@ -48,11 +51,13 @@ public class NameResolver extends Visitor { popScope(); } + @Override public void visit(LocalFuncDef stat) { defineLocalVar(stat.name); super.visit(stat); } + @Override public void visit(NumericFor stat) { pushScope(); stat.scope = scope; @@ -61,6 +66,7 @@ public class NameResolver extends Visitor { popScope(); } + @Override public void visit(GenericFor stat) { pushScope(); stat.scope = scope; @@ -69,39 +75,44 @@ public class NameResolver extends Visitor { popScope(); } + @Override public void visit(NameExp exp) { exp.name.variable = resolveNameReference(exp.name); super.visit(exp); } + @Override public void visit(FuncDef stat) { stat.name.name.variable = resolveNameReference(stat.name.name); stat.name.name.variable.hasassignments = true; super.visit(stat); } + @Override public void visit(Assign stat) { super.visit(stat); - for (int i = 0, n = stat.vars.size(); i < n; i++) { - VarExp v = (VarExp) stat.vars.get(i); + for (VarExp element : stat.vars) { + VarExp v = element; v.markHasAssignment(); } } + @Override public void visit(LocalAssign stat) { visitExps(stat.values); defineLocalVars(stat.names); int n = stat.names.size(); int m = stat.values != null? stat.values.size(): 0; - boolean isvarlist = m > 0 && m < n && ((Exp) stat.values.get(m-1)).isvarargexp(); + boolean isvarlist = m > 0 && m < n && stat.values.get(m-1).isvarargexp(); for (int i = 0; i < n && i < (isvarlist? m-1: m); i++) if (stat.values.get(i) instanceof Constant) - ((Name) stat.names.get(i)).variable.initialValue = ((Constant) stat.values.get(i)).value; + stat.names.get(i).variable.initialValue = ((Constant) stat.values.get(i)).value; if (!isvarlist) for (int i = m; i < n; i++) - ((Name) stat.names.get(i)).variable.initialValue = LuaValue.NIL; + stat.names.get(i).variable.initialValue = LuaValue.NIL; } + @Override public void visit(ParList pars) { if (pars.names != null) defineLocalVars(pars.names); @@ -111,8 +122,8 @@ public class NameResolver extends Visitor { } protected void defineLocalVars(List names) { - for (int i = 0, n = names.size(); i < n; i++) - defineLocalVar((Name) names.get(i)); + for (Name name : names) + defineLocalVar(name); } protected void defineLocalVar(Name name) { diff --git a/luaj-jse/src/main/java/org/luaj/vm2/ast/NameScope.java b/luaj-jse/src/main/java/org/luaj/vm2/ast/NameScope.java index 420e75ad..d7aaf55f 100644 --- a/luaj-jse/src/main/java/org/luaj/vm2/ast/NameScope.java +++ b/luaj-jse/src/main/java/org/luaj/vm2/ast/NameScope.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 @@ -28,16 +28,16 @@ import java.util.Set; public class NameScope { - private static final Set LUA_KEYWORDS = new HashSet(); + private static final Set LUA_KEYWORDS = new HashSet<>(); static { - String[] k = new String[] { "and", "break", "do", "else", "elseif", "end", "false", "for", "function", "if", - "in", "local", "nil", "not", "or", "repeat", "return", "then", "true", "until", "while" }; - for (int i = 0; i < k.length; i++) - LUA_KEYWORDS.add(k[i]); + String[] k = { "and", "break", "do", "else", "elseif", "end", "false", "for", "function", "if", "in", "local", + "nil", "not", "or", "repeat", "return", "then", "true", "until", "while" }; + for (String element : k) + LUA_KEYWORDS.add(element); } - public final Map namedVariables = new HashMap(); + public final Map namedVariables = new HashMap<>(); public final NameScope outerScope; @@ -63,7 +63,7 @@ public class NameScope { validateIsNotKeyword(name); for (NameScope n = this; n != null; n = n.outerScope) if (n.namedVariables.containsKey(name)) - return (Variable) n.namedVariables.get(name); + return n.namedVariables.get(name); Variable value = new Variable(name); this.namedVariables.put(name, value); return value; diff --git a/luaj-jse/src/main/java/org/luaj/vm2/ast/ParList.java b/luaj-jse/src/main/java/org/luaj/vm2/ast/ParList.java index a347eec9..87281c31 100644 --- a/luaj-jse/src/main/java/org/luaj/vm2/ast/ParList.java +++ b/luaj-jse/src/main/java/org/luaj/vm2/ast/ParList.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,7 +25,7 @@ import java.util.ArrayList; import java.util.List; public class ParList extends SyntaxElement { - public static final List EMPTY_NAMELIST = new ArrayList(); + public static final List EMPTY_NAMELIST = new ArrayList<>(); public static final ParList EMPTY_PARLIST = new ParList(EMPTY_NAMELIST, false); public final List names; diff --git a/luaj-jse/src/main/java/org/luaj/vm2/ast/Stat.java b/luaj-jse/src/main/java/org/luaj/vm2/ast/Stat.java index f3010460..3dbd3636 100644 --- a/luaj-jse/src/main/java/org/luaj/vm2/ast/Stat.java +++ b/luaj-jse/src/main/java/org/luaj/vm2/ast/Stat.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 @@ -96,6 +96,7 @@ abstract public class Stat extends SyntaxElement { this.name = name; } + @Override public void accept(Visitor visitor) { visitor.visit(this); } @@ -108,6 +109,7 @@ abstract public class Stat extends SyntaxElement { this.name = name; } + @Override public void accept(Visitor visitor) { visitor.visit(this); } @@ -122,6 +124,7 @@ abstract public class Stat extends SyntaxElement { this.exps = exps; } + @Override public void accept(Visitor visitor) { visitor.visit(this); } @@ -137,6 +140,7 @@ abstract public class Stat extends SyntaxElement { this.block = block; } + @Override public void accept(Visitor visitor) { visitor.visit(this); } @@ -151,12 +155,14 @@ abstract public class Stat extends SyntaxElement { this.exp = exp; } + @Override public void accept(Visitor visitor) { visitor.visit(this); } } public static class Break extends Stat { + @Override public void accept(Visitor visitor) { visitor.visit(this); } @@ -169,13 +175,14 @@ abstract public class Stat extends SyntaxElement { this.values = values; } + @Override public void accept(Visitor visitor) { visitor.visit(this); } public int nreturns() { int n = values != null? values.size(): 0; - if (n > 0 && ((Exp) values.get(n-1)).isvarargexp()) + if (n > 0 && values.get(n-1).isvarargexp()) n = -1; return n; } @@ -188,6 +195,7 @@ abstract public class Stat extends SyntaxElement { this.funccall = funccall; } + @Override public void accept(Visitor visitor) { visitor.visit(this); } @@ -202,6 +210,7 @@ abstract public class Stat extends SyntaxElement { this.body = body; } + @Override public void accept(Visitor visitor) { visitor.visit(this); } @@ -216,6 +225,7 @@ abstract public class Stat extends SyntaxElement { this.body = body; } + @Override public void accept(Visitor visitor) { visitor.visit(this); } @@ -233,6 +243,7 @@ abstract public class Stat extends SyntaxElement { this.block = block; } + @Override public void accept(Visitor visitor) { visitor.visit(this); } @@ -252,6 +263,7 @@ abstract public class Stat extends SyntaxElement { this.block = block; } + @Override public void accept(Visitor visitor) { visitor.visit(this); } @@ -266,6 +278,7 @@ abstract public class Stat extends SyntaxElement { this.values = values; } + @Override public void accept(Visitor visitor) { visitor.visit(this); } @@ -286,6 +299,7 @@ abstract public class Stat extends SyntaxElement { this.elseblock = elseblock; } + @Override public void accept(Visitor visitor) { visitor.visit(this); } diff --git a/luaj-jse/src/main/java/org/luaj/vm2/ast/Str.java b/luaj-jse/src/main/java/org/luaj/vm2/ast/Str.java index 6fd44eb8..db78662c 100644 --- a/luaj-jse/src/main/java/org/luaj/vm2/ast/Str.java +++ b/luaj-jse/src/main/java/org/luaj/vm2/ast/Str.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 @@ -74,9 +74,9 @@ public class Str { case '7': case '8': case '9': - int d = (int) (c[i++]-'0'); + int d = c[i++]-'0'; for (int j = 0; i < n && j < 2 && c[i] >= '0' && c[i] <= '9'; i++, j++) - d = d*10+(int) (c[i]-'0'); + d = d*10+c[i]-'0'; baos.write((byte) d); --i; continue; diff --git a/luaj-jse/src/main/java/org/luaj/vm2/ast/SyntaxElement.java b/luaj-jse/src/main/java/org/luaj/vm2/ast/SyntaxElement.java index f42c858b..767ec6c1 100644 --- a/luaj-jse/src/main/java/org/luaj/vm2/ast/SyntaxElement.java +++ b/luaj-jse/src/main/java/org/luaj/vm2/ast/SyntaxElement.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 diff --git a/luaj-jse/src/main/java/org/luaj/vm2/ast/TableConstructor.java b/luaj-jse/src/main/java/org/luaj/vm2/ast/TableConstructor.java index 69fd480b..dea98b82 100644 --- a/luaj-jse/src/main/java/org/luaj/vm2/ast/TableConstructor.java +++ b/luaj-jse/src/main/java/org/luaj/vm2/ast/TableConstructor.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,6 +26,7 @@ import java.util.List; public class TableConstructor extends Exp { public List fields; + @Override public void accept(Visitor visitor) { visitor.visit(this); } diff --git a/luaj-jse/src/main/java/org/luaj/vm2/ast/TableField.java b/luaj-jse/src/main/java/org/luaj/vm2/ast/TableField.java index 6a606586..0384fdf7 100644 --- a/luaj-jse/src/main/java/org/luaj/vm2/ast/TableField.java +++ b/luaj-jse/src/main/java/org/luaj/vm2/ast/TableField.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 diff --git a/luaj-jse/src/main/java/org/luaj/vm2/ast/Variable.java b/luaj-jse/src/main/java/org/luaj/vm2/ast/Variable.java index 69ff2e31..cee1ddaf 100644 --- a/luaj-jse/src/main/java/org/luaj/vm2/ast/Variable.java +++ b/luaj-jse/src/main/java/org/luaj/vm2/ast/Variable.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 diff --git a/luaj-jse/src/main/java/org/luaj/vm2/ast/Visitor.java b/luaj-jse/src/main/java/org/luaj/vm2/ast/Visitor.java index d33a6069..d3da74ac 100644 --- a/luaj-jse/src/main/java/org/luaj/vm2/ast/Visitor.java +++ b/luaj-jse/src/main/java/org/luaj/vm2/ast/Visitor.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 @@ -28,14 +28,14 @@ import org.luaj.vm2.ast.Exp.VarExp; abstract public class Visitor { public void visit(Chunk chunk) { chunk.block.accept(this); - }; + } public void visit(Block block) { visit(block.scope); if (block.stats != null) - for (int i = 0, n = block.stats.size(); i < n; i++) - ((Stat) block.stats.get(i)).accept(this); - }; + for (Stat element : block.stats) + element.accept(this); + } public void visit(Stat.Assign stat) { visitVars(stat.vars); @@ -65,8 +65,8 @@ abstract public class Visitor { stat.ifblock.accept(this); if (stat.elseifblocks != null) for (int i = 0, n = stat.elseifblocks.size(); i < n; i++) { - ((Exp) stat.elseifexps.get(i)).accept(this); - ((Block) stat.elseifblocks.get(i)).accept(this); + stat.elseifexps.get(i).accept(this); + stat.elseifblocks.get(i).accept(this); } if (stat.elseblock != null) visit(stat.elseblock); @@ -178,26 +178,26 @@ abstract public class Visitor { public void visit(TableConstructor table) { if (table.fields != null) - for (int i = 0, n = table.fields.size(); i < n; i++) - ((TableField) table.fields.get(i)).accept(this); + for (TableField element : table.fields) + element.accept(this); } public void visitVars(List vars) { if (vars != null) - for (int i = 0, n = vars.size(); i < n; i++) - ((Exp.VarExp) vars.get(i)).accept(this); + for (VarExp var : vars) + var.accept(this); } public void visitExps(List exps) { if (exps != null) - for (int i = 0, n = exps.size(); i < n; i++) - ((Exp) exps.get(i)).accept(this); + for (Exp exp : exps) + exp.accept(this); } public void visitNames(List names) { if (names != null) - for (int i = 0, n = names.size(); i < n; i++) - visit((Name) names.get(i)); + for (Name name : names) + visit(name); } public void visit(Name name) { diff --git a/luaj-jse/src/main/java/org/luaj/vm2/lib/jse/CoerceJavaToLua.java b/luaj-jse/src/main/java/org/luaj/vm2/lib/jse/CoerceJavaToLua.java index 59b2cdef..8bce0a2e 100644 --- a/luaj-jse/src/main/java/org/luaj/vm2/lib/jse/CoerceJavaToLua.java +++ b/luaj-jse/src/main/java/org/luaj/vm2/lib/jse/CoerceJavaToLua.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 @@ -58,17 +58,18 @@ import org.luaj.vm2.LuaValue; * The method {@link CoerceJavaToLua#coerce(Object)} looks as the type and * dimesioning of the argument and tries to guess the best fit for corrsponding * lua scalar, table, or table of tables. - * + * * @see CoerceJavaToLua#coerce(Object) * @see org.luaj.vm2.lib.jse.LuajavaLib */ public class CoerceJavaToLua { - static interface Coercion { - public LuaValue coerce(Object javaValue); - }; + interface Coercion { + LuaValue coerce(Object javaValue); + } private static final class BoolCoercion implements Coercion { + @Override public LuaValue coerce(Object javaValue) { Boolean b = (Boolean) javaValue; return b.booleanValue()? LuaValue.TRUE: LuaValue.FALSE; @@ -76,6 +77,7 @@ public class CoerceJavaToLua { } private static final class IntCoercion implements Coercion { + @Override public LuaValue coerce(Object javaValue) { Number n = (Number) javaValue; return LuaInteger.valueOf(n.intValue()); @@ -83,6 +85,7 @@ public class CoerceJavaToLua { } private static final class CharCoercion implements Coercion { + @Override public LuaValue coerce(Object javaValue) { Character c = (Character) javaValue; return LuaInteger.valueOf(c.charValue()); @@ -90,6 +93,7 @@ public class CoerceJavaToLua { } private static final class DoubleCoercion implements Coercion { + @Override public LuaValue coerce(Object javaValue) { Number n = (Number) javaValue; return LuaDouble.valueOf(n.doubleValue()); @@ -97,37 +101,43 @@ public class CoerceJavaToLua { } private static final class StringCoercion implements Coercion { + @Override public LuaValue coerce(Object javaValue) { return LuaString.valueOf(javaValue.toString()); } } private static final class BytesCoercion implements Coercion { + @Override public LuaValue coerce(Object javaValue) { return LuaValue.valueOf((byte[]) javaValue); } } private static final class ClassCoercion implements Coercion { + @Override public LuaValue coerce(Object javaValue) { return JavaClass.forClass((Class) javaValue); } } private static final class InstanceCoercion implements Coercion { + @Override public LuaValue coerce(Object javaValue) { return new JavaInstance(javaValue); } } private static final class ArrayCoercion implements Coercion { + @Override public LuaValue coerce(Object javaValue) { - // should be userdata? + // should be userdata? return new JavaArray(javaValue); } } private static final class LuaCoercion implements Coercion { + @Override public LuaValue coerce(Object javaValue) { return (LuaValue) javaValue; } @@ -165,7 +175,7 @@ public class CoerceJavaToLua { * {@code byte[]} will become {@link LuaString}; types inheriting from * {@link LuaValue} will be returned without coercion; other types will * become {@link LuaUserdata}. - * + * * @param o Java object needing conversion * @return {@link LuaValue} corresponding to the supplied Java value. * @see LuaValue diff --git a/luaj-jse/src/main/java/org/luaj/vm2/lib/jse/CoerceLuaToJava.java b/luaj-jse/src/main/java/org/luaj/vm2/lib/jse/CoerceLuaToJava.java index eb72abfc..c413f16d 100644 --- a/luaj-jse/src/main/java/org/luaj/vm2/lib/jse/CoerceLuaToJava.java +++ b/luaj-jse/src/main/java/org/luaj/vm2/lib/jse/CoerceLuaToJava.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 @@ -53,7 +53,7 @@ import org.luaj.vm2.LuaValue; *

    * For data in lua tables, the various methods on {@link LuaTable} can be used * directly to convert data to something more useful. - * + * * @see org.luaj.vm2.lib.jse.LuajavaLib * @see CoerceJavaToLua */ @@ -63,15 +63,15 @@ public class CoerceLuaToJava { static int SCORE_WRONG_TYPE = 0x100; static int SCORE_UNCOERCIBLE = 0x10000; - static interface Coercion { - public int score(LuaValue value); + interface Coercion { + int score(LuaValue value); - public Object coerce(LuaValue value); - }; + Object coerce(LuaValue value); + } /** * Coerce a LuaValue value to a specified java class - * + * * @param value LuaValue to coerce * @param clazz Class to coerce into * @return Object of type clazz (or a subclass) with the corresponding @@ -84,10 +84,12 @@ public class CoerceLuaToJava { static final Map COERCIONS = Collections.synchronizedMap(new HashMap()); static final class BoolCoercion implements Coercion { + @Override public String toString() { return "BoolCoercion()"; } + @Override public int score(LuaValue value) { switch (value.type()) { case LuaValue.TBOOLEAN: @@ -96,6 +98,7 @@ public class CoerceLuaToJava { return 1; } + @Override public Object coerce(LuaValue value) { return value.toboolean()? Boolean.TRUE: Boolean.FALSE; } @@ -112,6 +115,7 @@ public class CoerceLuaToJava { static final String[] TYPE_NAMES = { "byte", "char", "short", "int", "long", "float", "double" }; final int targetType; + @Override public String toString() { return "NumericCoercion(" + TYPE_NAMES[targetType] + ")"; } @@ -120,6 +124,7 @@ public class CoerceLuaToJava { this.targetType = targetType; } + @Override public int score(LuaValue value) { int fromStringPenalty = 0; if (value.type() == LuaValue.TSTRING) { @@ -133,19 +138,19 @@ public class CoerceLuaToJava { switch (targetType) { case TARGET_TYPE_BYTE: { int i = value.toint(); - return fromStringPenalty+((i == (byte) i)? 0: SCORE_WRONG_TYPE); + return fromStringPenalty+(i == (byte) i? 0: SCORE_WRONG_TYPE); } case TARGET_TYPE_CHAR: { int i = value.toint(); - return fromStringPenalty+((i == (byte) i)? 1: (i == (char) i)? 0: SCORE_WRONG_TYPE); + return fromStringPenalty+(i == (byte) i? 1: i == (char) i? 0: SCORE_WRONG_TYPE); } case TARGET_TYPE_SHORT: { int i = value.toint(); - return fromStringPenalty+((i == (byte) i)? 1: (i == (short) i)? 0: SCORE_WRONG_TYPE); + return fromStringPenalty+(i == (byte) i? 1: i == (short) i? 0: SCORE_WRONG_TYPE); } case TARGET_TYPE_INT: { int i = value.toint(); - return fromStringPenalty+((i == (byte) i)? 2: ((i == (char) i) || (i == (short) i))? 1: 0); + return fromStringPenalty+(i == (byte) i? 2: i == (char) i || i == (short) i? 1: 0); } case TARGET_TYPE_FLOAT: return fromStringPenalty+1; @@ -168,15 +173,15 @@ public class CoerceLuaToJava { return SCORE_WRONG_TYPE; case TARGET_TYPE_LONG: { double d = value.todouble(); - return fromStringPenalty+((d == (long) d)? 0: SCORE_WRONG_TYPE); + return fromStringPenalty+(d == (long) d? 0: SCORE_WRONG_TYPE); } case TARGET_TYPE_FLOAT: { double d = value.todouble(); - return fromStringPenalty+((d == (float) d)? 0: SCORE_WRONG_TYPE); + return fromStringPenalty+(d == (float) d? 0: SCORE_WRONG_TYPE); } case TARGET_TYPE_DOUBLE: { double d = value.todouble(); - return fromStringPenalty+(((d == (long) d) || (d == (float) d))? 1: 0); + return fromStringPenalty+(d == (long) d || d == (float) d? 1: 0); } default: return SCORE_WRONG_TYPE; @@ -186,22 +191,23 @@ public class CoerceLuaToJava { } } + @Override public Object coerce(LuaValue value) { switch (targetType) { case TARGET_TYPE_BYTE: - return new Byte((byte) value.toint()); + return Byte.valueOf((byte) value.toint()); case TARGET_TYPE_CHAR: - return new Character((char) value.toint()); + return Character.valueOf((char) value.toint()); case TARGET_TYPE_SHORT: - return new Short((short) value.toint()); + return Short.valueOf((short) value.toint()); case TARGET_TYPE_INT: - return new Integer((int) value.toint()); + return Integer.valueOf(value.toint()); case TARGET_TYPE_LONG: - return new Long((long) value.todouble()); + return Long.valueOf((long) value.todouble()); case TARGET_TYPE_FLOAT: - return new Float((float) value.todouble()); + return Float.valueOf((float) value.todouble()); case TARGET_TYPE_DOUBLE: - return new Double((double) value.todouble()); + return Double.valueOf(value.todouble()); default: return null; } @@ -217,15 +223,17 @@ public class CoerceLuaToJava { this.targetType = targetType; } + @Override public String toString() { return "StringCoercion(" + (targetType == TARGET_TYPE_STRING? "String": "byte[]") + ")"; } + @Override public int score(LuaValue value) { switch (value.type()) { case LuaValue.TSTRING: - return value.checkstring().isValidUtf8()? (targetType == TARGET_TYPE_STRING? 0: 1) - : (targetType == TARGET_TYPE_BYTES? 0: SCORE_WRONG_TYPE); + return value.checkstring().isValidUtf8()? targetType == TARGET_TYPE_STRING? 0: 1 + : targetType == TARGET_TYPE_BYTES? 0: SCORE_WRONG_TYPE; case LuaValue.TNIL: return SCORE_NULL_VALUE; default: @@ -233,6 +241,7 @@ public class CoerceLuaToJava { } } + @Override public Object coerce(LuaValue value) { if (value.isnil()) return null; @@ -254,10 +263,12 @@ public class CoerceLuaToJava { this.componentCoercion = getCoercion(componentType); } + @Override public String toString() { return "ArrayCoercion(" + componentType.getName() + ")"; } + @Override public int score(LuaValue value) { switch (value.type()) { case LuaValue.TTABLE: @@ -271,6 +282,7 @@ public class CoerceLuaToJava { } } + @Override public Object coerce(LuaValue value) { switch (value.type()) { case LuaValue.TTABLE: { @@ -293,7 +305,7 @@ public class CoerceLuaToJava { /** * Determine levels of inheritance between a base class and a subclass - * + * * @param baseclass base class to look for * @param subclass class from which to start looking * @return number of inheritance levels between subclass and baseclass, or @@ -306,8 +318,8 @@ public class CoerceLuaToJava { return 0; int min = Math.min(SCORE_UNCOERCIBLE, inheritanceLevels(baseclass, subclass.getSuperclass())+1); Class[] ifaces = subclass.getInterfaces(); - for (int i = 0; i < ifaces.length; i++) - min = Math.min(min, inheritanceLevels(baseclass, ifaces[i])+1); + for (Class element : ifaces) + min = Math.min(min, inheritanceLevels(baseclass, element)+1); return min; } @@ -318,10 +330,12 @@ public class CoerceLuaToJava { this.targetType = targetType; } + @Override public String toString() { return "ObjectCoercion(" + targetType.getName() + ")"; } + @Override public int score(LuaValue value) { switch (value.type()) { case LuaValue.TNUMBER: @@ -339,10 +353,12 @@ public class CoerceLuaToJava { } } + @Override public Object coerce(LuaValue value) { switch (value.type()) { case LuaValue.TNUMBER: - return value.isint()? (Object) new Integer(value.toint()): (Object) new Double(value.todouble()); + return value.isint()? (Object) Integer.valueOf(value.toint()) + : (Object) Double.valueOf(value.todouble()); case LuaValue.TBOOLEAN: return value.toboolean()? Boolean.TRUE: Boolean.FALSE; case LuaValue.TSTRING: diff --git a/luaj-jse/src/main/java/org/luaj/vm2/lib/jse/JavaArray.java b/luaj-jse/src/main/java/org/luaj/vm2/lib/jse/JavaArray.java index 079afc6b..59fbfe11 100644 --- a/luaj-jse/src/main/java/org/luaj/vm2/lib/jse/JavaArray.java +++ b/luaj-jse/src/main/java/org/luaj/vm2/lib/jse/JavaArray.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 @@ -35,13 +35,14 @@ import org.luaj.vm2.lib.OneArgFunction; *

    * This class is not used directly. It is returned by calls to * {@link CoerceJavaToLua#coerce(Object)} when an array is supplied. - * + * * @see CoerceJavaToLua * @see CoerceLuaToJava */ class JavaArray extends LuaUserdata { private static final class LenFunction extends OneArgFunction { + @Override public LuaValue call(LuaValue u) { return LuaValue.valueOf(Array.getLength(((LuaUserdata) u).m_instance)); } @@ -60,6 +61,7 @@ class JavaArray extends LuaUserdata { setmetatable(array_metatable); } + @Override public LuaValue get(LuaValue key) { if (key.equals(LENGTH)) return valueOf(Array.getLength(m_instance)); @@ -72,6 +74,7 @@ class JavaArray extends LuaUserdata { return super.get(key); } + @Override public void set(LuaValue key, LuaValue value) { if (key.isint()) { int i = key.toint()-1; diff --git a/luaj-jse/src/main/java/org/luaj/vm2/lib/jse/JavaClass.java b/luaj-jse/src/main/java/org/luaj/vm2/lib/jse/JavaClass.java index 235d6c2e..efe45319 100644 --- a/luaj-jse/src/main/java/org/luaj/vm2/lib/jse/JavaClass.java +++ b/luaj-jse/src/main/java/org/luaj/vm2/lib/jse/JavaClass.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 @@ -42,7 +42,7 @@ import org.luaj.vm2.LuaValue; *

    * This class is not used directly. It is returned by calls to * {@link CoerceJavaToLua#coerce(Object)} when a Class is supplied. - * + * * @see CoerceJavaToLua * @see CoerceLuaToJava */ @@ -68,6 +68,7 @@ class JavaClass extends JavaInstance implements CoerceJavaToLua.Coercion { this.jclass = this; } + @Override public LuaValue coerce(Object javaValue) { return this; } @@ -76,8 +77,7 @@ class JavaClass extends JavaInstance implements CoerceJavaToLua.Coercion { if (fields == null) { Map m = new HashMap(); Field[] f = ((Class) m_instance).getFields(); - for (int i = 0; i < f.length; i++) { - Field fi = f[i]; + for (Field fi : f) { if (Modifier.isPublic(fi.getModifiers())) { m.put(LuaValue.valueOf(fi.getName()), fi); try { @@ -96,8 +96,7 @@ class JavaClass extends JavaInstance implements CoerceJavaToLua.Coercion { if (methods == null) { Map namedlists = new HashMap(); Method[] m = ((Class) m_instance).getMethods(); - for (int i = 0; i < m.length; i++) { - Method mi = m[i]; + for (Method mi : m) { if (Modifier.isPublic(mi.getModifiers())) { String name = mi.getName(); List list = (List) namedlists.get(name); @@ -109,9 +108,9 @@ class JavaClass extends JavaInstance implements CoerceJavaToLua.Coercion { Map map = new HashMap(); Constructor[] c = ((Class) m_instance).getConstructors(); List list = new ArrayList(); - for (int i = 0; i < c.length; i++) - if (Modifier.isPublic(c[i].getModifiers())) - list.add(JavaConstructor.forConstructor(c[i])); + for (Constructor element : c) + if (Modifier.isPublic(element.getModifiers())) + list.add(JavaConstructor.forConstructor(element)); switch (list.size()) { case 0: break; @@ -140,8 +139,7 @@ class JavaClass extends JavaInstance implements CoerceJavaToLua.Coercion { if (innerclasses == null) { Map m = new HashMap(); Class[] c = ((Class) m_instance).getClasses(); - for (int i = 0; i < c.length; i++) { - Class ci = c[i]; + for (Class ci : c) { String name = ci.getName(); String stub = name.substring(Math.max(name.lastIndexOf('$'), name.lastIndexOf('.'))+1); m.put(LuaValue.valueOf(stub), ci); diff --git a/luaj-jse/src/main/java/org/luaj/vm2/lib/jse/JavaConstructor.java b/luaj-jse/src/main/java/org/luaj/vm2/lib/jse/JavaConstructor.java index aefd4648..5efea09d 100644 --- a/luaj-jse/src/main/java/org/luaj/vm2/lib/jse/JavaConstructor.java +++ b/luaj-jse/src/main/java/org/luaj/vm2/lib/jse/JavaConstructor.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 @@ -40,7 +40,7 @@ import org.luaj.vm2.lib.VarArgFunction; *

    * This class is not used directly. It is returned by calls to * {@link JavaClass#new(LuaValue key)} when the value of key is "new". - * + * * @see CoerceJavaToLua * @see CoerceLuaToJava */ @@ -66,6 +66,7 @@ class JavaConstructor extends JavaMember { this.constructor = c; } + @Override public Varargs invoke(Varargs args) { Object[] a = convertArgs(args); try { @@ -93,20 +94,21 @@ class JavaConstructor extends JavaMember { this.constructors = c; } + @Override public Varargs invoke(Varargs args) { JavaConstructor best = null; int score = CoerceLuaToJava.SCORE_UNCOERCIBLE; - for (int i = 0; i < constructors.length; i++) { - int s = constructors[i].score(args); + for (JavaConstructor constructor : constructors) { + int s = constructor.score(args); if (s < score) { score = s; - best = constructors[i]; + best = constructor; if (score == 0) break; } } - // any match? + // any match? if (best == null) LuaValue.error("no coercible public method"); diff --git a/luaj-jse/src/main/java/org/luaj/vm2/lib/jse/JavaInstance.java b/luaj-jse/src/main/java/org/luaj/vm2/lib/jse/JavaInstance.java index d3ac3c83..d24cc025 100644 --- a/luaj-jse/src/main/java/org/luaj/vm2/lib/jse/JavaInstance.java +++ b/luaj-jse/src/main/java/org/luaj/vm2/lib/jse/JavaInstance.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 @@ -34,7 +34,7 @@ import org.luaj.vm2.LuaValue; *

    * This class is not used directly. It is returned by calls to * {@link CoerceJavaToLua#coerce(Object)} when a subclass of Object is supplied. - * + * * @see CoerceJavaToLua * @see CoerceLuaToJava */ @@ -46,6 +46,7 @@ class JavaInstance extends LuaUserdata { super(instance); } + @Override public LuaValue get(LuaValue key) { if (jclass == null) jclass = JavaClass.forClass(m_instance.getClass()); @@ -65,6 +66,7 @@ class JavaInstance extends LuaUserdata { return super.get(key); } + @Override public void set(LuaValue key, LuaValue value) { if (jclass == null) jclass = JavaClass.forClass(m_instance.getClass()); diff --git a/luaj-jse/src/main/java/org/luaj/vm2/lib/jse/JavaMember.java b/luaj-jse/src/main/java/org/luaj/vm2/lib/jse/JavaMember.java index 886b7c40..f63e01c1 100644 --- a/luaj-jse/src/main/java/org/luaj/vm2/lib/jse/JavaMember.java +++ b/luaj-jse/src/main/java/org/luaj/vm2/lib/jse/JavaMember.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 @@ -33,7 +33,7 @@ import org.luaj.vm2.lib.jse.CoerceLuaToJava.Coercion; *

    * This class is not used directly. It is an abstract base class for * {@link JavaConstructor} and {@link JavaMethod}. - * + * * @see JavaConstructor * @see JavaMethod * @see CoerceJavaToLua @@ -47,7 +47,7 @@ abstract class JavaMember extends VarArgFunction { final Coercion varargs; protected JavaMember(Class[] params, int modifiers) { - boolean isvarargs = ((modifiers & METHOD_MODIFIERS_VARARGS) != 0); + boolean isvarargs = (modifiers & METHOD_MODIFIERS_VARARGS) != 0; fixedargs = new CoerceLuaToJava.Coercion[isvarargs? params.length-1: params.length]; for (int i = 0; i < fixedargs.length; i++) fixedargs[i] = CoerceLuaToJava.getCoercion(params[i]); diff --git a/luaj-jse/src/main/java/org/luaj/vm2/lib/jse/JavaMethod.java b/luaj-jse/src/main/java/org/luaj/vm2/lib/jse/JavaMethod.java index 3d478d84..2beb04e0 100644 --- a/luaj-jse/src/main/java/org/luaj/vm2/lib/jse/JavaMethod.java +++ b/luaj-jse/src/main/java/org/luaj/vm2/lib/jse/JavaMethod.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 @@ -39,7 +39,7 @@ import org.luaj.vm2.Varargs; *

    * This class is not used directly. It is returned by calls to calls to * {@link JavaInstance#get(LuaValue key)} when a method is named. - * + * * @see CoerceJavaToLua * @see CoerceLuaToJava */ @@ -70,22 +70,27 @@ class JavaMethod extends JavaMember { } } + @Override public LuaValue call() { return error("method cannot be called without instance"); } + @Override public LuaValue call(LuaValue arg) { return invokeMethod(arg.checkuserdata(), LuaValue.NONE); } + @Override public LuaValue call(LuaValue arg1, LuaValue arg2) { return invokeMethod(arg1.checkuserdata(), arg2); } + @Override public LuaValue call(LuaValue arg1, LuaValue arg2, LuaValue arg3) { return invokeMethod(arg1.checkuserdata(), LuaValue.varargsOf(arg2, arg3)); } + @Override public Varargs invoke(Varargs args) { return invokeMethod(args.checkuserdata(1), args.subargs(2)); } @@ -118,22 +123,27 @@ class JavaMethod extends JavaMember { this.methods = methods; } + @Override public LuaValue call() { return error("method cannot be called without instance"); } + @Override public LuaValue call(LuaValue arg) { return invokeBestMethod(arg.checkuserdata(), LuaValue.NONE); } + @Override public LuaValue call(LuaValue arg1, LuaValue arg2) { return invokeBestMethod(arg1.checkuserdata(), arg2); } + @Override public LuaValue call(LuaValue arg1, LuaValue arg2, LuaValue arg3) { return invokeBestMethod(arg1.checkuserdata(), LuaValue.varargsOf(arg2, arg3)); } + @Override public Varargs invoke(Varargs args) { return invokeBestMethod(args.checkuserdata(1), args.subargs(2)); } @@ -141,17 +151,17 @@ class JavaMethod extends JavaMember { private LuaValue invokeBestMethod(Object instance, Varargs args) { JavaMethod best = null; int score = CoerceLuaToJava.SCORE_UNCOERCIBLE; - for (int i = 0; i < methods.length; i++) { - int s = methods[i].score(args); + for (JavaMethod method : methods) { + int s = method.score(args); if (s < score) { score = s; - best = methods[i]; + best = method; if (score == 0) break; } } - // any match? + // any match? if (best == null) LuaValue.error("no coercible public method"); diff --git a/luaj-jse/src/main/java/org/luaj/vm2/lib/jse/JseBaseLib.java b/luaj-jse/src/main/java/org/luaj/vm2/lib/jse/JseBaseLib.java index a1fa5dcd..cd94d590 100644 --- a/luaj-jse/src/main/java/org/luaj/vm2/lib/jse/JseBaseLib.java +++ b/luaj-jse/src/main/java/org/luaj/vm2/lib/jse/JseBaseLib.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 @@ -47,7 +47,7 @@ import org.luaj.vm2.lib.ResourceFinder; *

    * Typically, this library is included as part of a call to * {@link org.luaj.vm2.lib.jse.JsePlatform#standardGlobals()} - * + * *

      * {
      * 	@code
    @@ -59,7 +59,7 @@ import org.luaj.vm2.lib.ResourceFinder;
      * For special cases where the smallest possible footprint is desired, a minimal
      * set of libraries could be loaded directly via {@link Globals#load(LuaValue)}
      * using code such as:
    - * 
    + *
      * 
      * {
      * 	@code
    @@ -73,7 +73,7 @@ import org.luaj.vm2.lib.ResourceFinder;
      * case.
      * 

    * This is a direct port of the corresponding library in C. - * + * * @see Globals * @see BaseLib * @see ResourceFinder @@ -95,11 +95,12 @@ public class JseBaseLib extends org.luaj.vm2.lib.BaseLib { *

    * Specifically, extend the library loading to set the default value for * {@link Globals#STDIN} - * + * * @param modname the module name supplied if this is loaded via 'require'. * @param env the environment to load into, which must be a Globals * instance. */ + @Override public LuaValue call(LuaValue modname, LuaValue env) { super.call(modname, env); env.checkglobals().STDIN = System.in; @@ -109,17 +110,18 @@ public class JseBaseLib extends org.luaj.vm2.lib.BaseLib { /** * Try to open a file in the current working directory, or fall back to base * opener if not found. - * + * * This implementation attempts to open the file using new File(filename). * It falls back to the base implementation that looks it up as a resource * in the class path if not found as a plain file. - * + * * @see org.luaj.vm2.lib.BaseLib * @see org.luaj.vm2.lib.ResourceFinder - * + * * @param filename * @return InputStream, or null if not found. */ + @Override public InputStream findResource(String filename) { File f = new File(filename); if (!f.exists()) diff --git a/luaj-jse/src/main/java/org/luaj/vm2/lib/jse/JseIoLib.java b/luaj-jse/src/main/java/org/luaj/vm2/lib/jse/JseIoLib.java index 99d4b6ac..36e560d6 100644 --- a/luaj-jse/src/main/java/org/luaj/vm2/lib/jse/JseIoLib.java +++ b/luaj-jse/src/main/java/org/luaj/vm2/lib/jse/JseIoLib.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 @@ -44,7 +44,7 @@ import org.luaj.vm2.lib.LibFunction; *

    * Typically, this library is included as part of a call to * {@link org.luaj.vm2.lib.jse.JsePlatform#standardGlobals()} - * + * *

      * {
      * 	@code
    @@ -56,7 +56,7 @@ import org.luaj.vm2.lib.LibFunction;
      * For special cases where the smallest possible footprint is desired, a minimal
      * set of libraries could be loaded directly via {@link Globals#load(LuaValue)}
      * using code such as:
    - * 
    + *
      * 
      * {
      * 	@code
    @@ -73,7 +73,7 @@ import org.luaj.vm2.lib.LibFunction;
      * 

    * This has been implemented to match as closely as possible the behavior in the * corresponding library in C. - * + * * @see LibFunction * @see org.luaj.vm2.lib.jse.JsePlatform * @see org.luaj.vm2.lib.jme.JmePlatform @@ -84,18 +84,22 @@ import org.luaj.vm2.lib.LibFunction; */ public class JseIoLib extends IoLib { + @Override protected File wrapStdin() throws IOException { return new StdinFile(); } + @Override protected File wrapStdout() throws IOException { return new StdoutFile(FTYPE_STDOUT); } + @Override protected File wrapStderr() throws IOException { return new StdoutFile(FTYPE_STDERR); } + @Override protected File openFile(String filename, boolean readMode, boolean appendMode, boolean updateMode, boolean binaryMode) throws IOException { RandomAccessFile f = new RandomAccessFile(filename, readMode? "r": "rw"); @@ -108,11 +112,13 @@ public class JseIoLib extends IoLib { return new FileImpl(f); } + @Override protected File openProgram(String prog, String mode) throws IOException { final Process p = Runtime.getRuntime().exec(prog); return "w".equals(mode)? new FileImpl(p.getOutputStream()): new FileImpl(p.getInputStream()); } + @Override protected File tmpFile() throws IOException { java.io.File f = java.io.File.createTempFile(".luaj", "bin"); f.deleteOnExit(); @@ -148,14 +154,17 @@ public class JseIoLib extends IoLib { this(null, null, o); } + @Override public String tojstring() { return "file (" + (this.closed? "closed": String.valueOf(this.hashCode())) + ")"; } + @Override public boolean isstdfile() { return file == null; } + @Override public void close() throws IOException { closed = true; if (file != null) { @@ -163,11 +172,13 @@ public class JseIoLib extends IoLib { } } + @Override public void flush() throws IOException { if (os != null) os.flush(); } + @Override public void write(LuaString s) throws IOException { if (os != null) os.write(s.m_bytes, s.m_offset, s.m_length); @@ -179,10 +190,12 @@ public class JseIoLib extends IoLib { flush(); } + @Override public boolean isclosed() { return closed; } + @Override public int seek(String option, int pos) throws IOException { if (file != null) { if ("set".equals(option)) { @@ -198,16 +211,19 @@ public class JseIoLib extends IoLib { return 0; } + @Override public void setvbuf(String mode, int size) { nobuffer = "no".equals(mode); } // get length remaining to read + @Override public int remaining() throws IOException { return file != null? (int) (file.length()-file.getFilePointer()): -1; } // peek ahead one character + @Override public int peek() throws IOException { if (is != null) { is.mark(1); @@ -225,6 +241,7 @@ public class JseIoLib extends IoLib { } // return char if read, -1 if eof, throw IOException on other exception + @Override public int read() throws IOException { if (is != null) return is.read(); @@ -236,6 +253,7 @@ public class JseIoLib extends IoLib { } // return number of bytes read if positive, -1 if eof, throws IOException + @Override public int read(byte[] bytes, int offset, int length) throws IOException { if (file != null) { return file.read(bytes, offset, length); @@ -255,51 +273,63 @@ public class JseIoLib extends IoLib { this.file_type = file_type; } + @Override public String tojstring() { return "file (" + this.hashCode() + ")"; } - private final PrintStream getPrintStream() { return file_type == FTYPE_STDERR? globals.STDERR: globals.STDOUT; } + private PrintStream getPrintStream() { return file_type == FTYPE_STDERR? globals.STDERR: globals.STDOUT; } + @Override public void write(LuaString string) throws IOException { getPrintStream().write(string.m_bytes, string.m_offset, string.m_length); } + @Override public void flush() throws IOException { getPrintStream().flush(); } + @Override public boolean isstdfile() { return true; } + @Override public void close() throws IOException { // do not close std files. } + @Override public boolean isclosed() { return false; } + @Override public int seek(String option, int bytecount) throws IOException { return 0; } + @Override public void setvbuf(String mode, int size) { } + @Override public int remaining() throws IOException { return 0; } + @Override public int peek() throws IOException, EOFException { return 0; } + @Override public int read() throws IOException, EOFException { return 0; } + @Override public int read(byte[] bytes, int offset, int length) throws IOException { return 0; } @@ -309,39 +339,49 @@ public class JseIoLib extends IoLib { private StdinFile() { } + @Override public String tojstring() { return "file (" + this.hashCode() + ")"; } + @Override public void write(LuaString string) throws IOException { } + @Override public void flush() throws IOException { } + @Override public boolean isstdfile() { return true; } + @Override public void close() throws IOException { // do not close std files. } + @Override public boolean isclosed() { return false; } + @Override public int seek(String option, int bytecount) throws IOException { return 0; } + @Override public void setvbuf(String mode, int size) { } + @Override public int remaining() throws IOException { return -1; } + @Override public int peek() throws IOException, EOFException { globals.STDIN.mark(1); int c = globals.STDIN.read(); @@ -349,10 +389,12 @@ public class JseIoLib extends IoLib { return c; } + @Override public int read() throws IOException, EOFException { return globals.STDIN.read(); } + @Override public int read(byte[] bytes, int offset, int length) throws IOException { return globals.STDIN.read(bytes, offset, length); } diff --git a/luaj-jse/src/main/java/org/luaj/vm2/lib/jse/JseMathLib.java b/luaj-jse/src/main/java/org/luaj/vm2/lib/jse/JseMathLib.java index 516f8277..aeb12244 100644 --- a/luaj-jse/src/main/java/org/luaj/vm2/lib/jse/JseMathLib.java +++ b/luaj-jse/src/main/java/org/luaj/vm2/lib/jse/JseMathLib.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 @@ -35,7 +35,7 @@ import org.luaj.vm2.lib.TwoArgFunction; *

    * Typically, this library is included as part of a call to * {@link org.luaj.vm2.lib.jse.JsePlatform#standardGlobals()} - * + * *

      * {
      * 	@code
    @@ -47,7 +47,7 @@ import org.luaj.vm2.lib.TwoArgFunction;
      * For special cases where the smallest possible footprint is desired, a minimal
      * set of libraries could be loaded directly via {@link Globals#load(LuaValue)}
      * using code such as:
    - * 
    + *
      * 
      * {
      * 	@code
    @@ -64,7 +64,7 @@ import org.luaj.vm2.lib.TwoArgFunction;
      * 

    * This has been implemented to match as closely as possible the behavior in the * corresponding library in C. - * + * * @see LibFunction * @see org.luaj.vm2.lib.jse.JsePlatform * @see org.luaj.vm2.lib.jme.JmePlatform @@ -85,11 +85,12 @@ public class JseMathLib extends org.luaj.vm2.lib.MathLib { * Specifically, adds all library functions that can be implemented directly * in JSE but not JME: acos, asin, atan, atan2, cosh, exp, log, pow, sinh, * and tanh. - * + * * @param modname the module name supplied if this is loaded via 'require'. * @param env the environment to load into, which must be a Globals * instance. */ + @Override public LuaValue call(LuaValue modname, LuaValue env) { super.call(modname, env); LuaValue math = env.get("math"); @@ -108,28 +109,34 @@ public class JseMathLib extends org.luaj.vm2.lib.MathLib { } static final class acos extends UnaryOp { + @Override protected double call(double d) { return Math.acos(d); } } static final class asin extends UnaryOp { + @Override protected double call(double d) { return Math.asin(d); } } static final class atan2 extends TwoArgFunction { + @Override public LuaValue call(LuaValue x, LuaValue y) { return valueOf(Math.atan2(x.checkdouble(), y.optdouble(1))); } } static final class cosh extends UnaryOp { + @Override protected double call(double d) { return Math.cosh(d); } } static final class exp extends UnaryOp { + @Override protected double call(double d) { return Math.exp(d); } } static final class log extends TwoArgFunction { + @Override public LuaValue call(LuaValue x, LuaValue base) { double nat = Math.log(x.checkdouble()); double b = base.optdouble(Math.E); @@ -140,18 +147,22 @@ public class JseMathLib extends org.luaj.vm2.lib.MathLib { } static final class pow extends BinaryOp { + @Override protected double call(double x, double y) { return Math.pow(x, y); } } static final class sinh extends UnaryOp { + @Override protected double call(double d) { return Math.sinh(d); } } static final class tanh extends UnaryOp { + @Override protected double call(double d) { return Math.tanh(d); } } /** Faster, better version of pow() used by arithmetic operator ^ */ + @Override public double dpow_lib(double a, double b) { return Math.pow(a, b); } diff --git a/luaj-jse/src/main/java/org/luaj/vm2/lib/jse/JseOsLib.java b/luaj-jse/src/main/java/org/luaj/vm2/lib/jse/JseOsLib.java index af21d7cc..42819775 100644 --- a/luaj-jse/src/main/java/org/luaj/vm2/lib/jse/JseOsLib.java +++ b/luaj-jse/src/main/java/org/luaj/vm2/lib/jse/JseOsLib.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 @@ -49,7 +49,7 @@ import org.luaj.vm2.lib.OsLib; *

    * Typically, this library is included as part of a call to * {@link org.luaj.vm2.lib.jse.JsePlatform#standardGlobals()} - * + * *

      * {
      * 	@code
    @@ -61,7 +61,7 @@ import org.luaj.vm2.lib.OsLib;
      * For special cases where the smallest possible footprint is desired, a minimal
      * set of libraries could be loaded directly via {@link Globals#load(LuaValue)}
      * using code such as:
    - * 
    + *
      * 
      * {
      * 	@code
    @@ -76,7 +76,7 @@ import org.luaj.vm2.lib.OsLib;
      * However, other libraries such as MathLib are not loaded in this
      * case.
      * 

    - * + * * @see LibFunction * @see OsLib * @see org.luaj.vm2.lib.jse.JsePlatform @@ -99,11 +99,13 @@ public class JseOsLib extends org.luaj.vm2.lib.OsLib { public JseOsLib() { } + @Override protected String getenv(String varname) { String s = System.getenv(varname); return s != null? s: System.getProperty(varname); } + @Override protected Varargs execute(String command) { int exitValue; try { @@ -120,6 +122,7 @@ public class JseOsLib extends org.luaj.vm2.lib.OsLib { return varargsOf(NIL, valueOf("signal"), valueOf(exitValue)); } + @Override protected void remove(String filename) throws IOException { File f = new File(filename); if (!f.exists()) @@ -128,6 +131,7 @@ public class JseOsLib extends org.luaj.vm2.lib.OsLib { throw new IOException("Failed to delete"); } + @Override protected void rename(String oldname, String newname) throws IOException { File f = new File(oldname); if (!f.exists()) @@ -136,6 +140,7 @@ public class JseOsLib extends org.luaj.vm2.lib.OsLib { throw new IOException("Failed to rename"); } + @Override protected String tmpname() { try { java.io.File f = java.io.File.createTempFile(TMP_PREFIX, TMP_SUFFIX); diff --git a/luaj-jse/src/main/java/org/luaj/vm2/lib/jse/JsePlatform.java b/luaj-jse/src/main/java/org/luaj/vm2/lib/jse/JsePlatform.java index 7c5954b6..63a01c0c 100644 --- a/luaj-jse/src/main/java/org/luaj/vm2/lib/jse/JsePlatform.java +++ b/luaj-jse/src/main/java/org/luaj/vm2/lib/jse/JsePlatform.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 @@ -42,7 +42,7 @@ import org.luaj.vm2.lib.TableLib; * {@link #standardGlobals()} or debug globals using {@link #debugGlobals()} *

    * A simple example of initializing globals and using them from Java is: - * + * *

      * {
      * 	@code
    @@ -52,7 +52,7 @@ import org.luaj.vm2.lib.TableLib;
      * 
    *

    * Once globals are created, a simple way to load and run a script is: - * + * *

      *  {@code
      * globals.load( new FileInputStream("main.lua"), "main.lua" ).call();
    @@ -60,13 +60,13 @@ import org.luaj.vm2.lib.TableLib;
      * 
    *

    * although {@code require} could also be used: - * + * *

      *  {@code
      * globals.get("require").call(LuaValue.valueOf("main"));
      * }
      * 
    - * + * * For this to succeed, the file "main.lua" must be in the current directory or * a resource. See {@link org.luaj.vm2.lib.jse.JseBaseLib} for details on * finding scripts using {@link ResourceFinder}. @@ -93,7 +93,7 @@ import org.luaj.vm2.lib.TableLib; * library {@link DebugLib}. *

    * The class ensures that initialization is done in the correct order. - * + * * @see Globals * @see org.luaj.vm2.lib.jme.JmePlatform */ @@ -101,7 +101,7 @@ public class JsePlatform { /** * Create a standard set of globals for JSE including all the libraries. - * + * * @return Table of globals initialized with the standard JSE libraries * @see #debugGlobals() * @see org.luaj.vm2.lib.jse.JsePlatform @@ -126,7 +126,7 @@ public class JsePlatform { /** * Create standard globals including the {@link DebugLib} library. - * + * * @return Table of globals initialized with the standard JSE and debug * libraries * @see #standardGlobals() @@ -144,7 +144,7 @@ public class JsePlatform { * Simple wrapper for invoking a lua function with command line arguments. * The supplied function is first given a new Globals object as its * environment then the program is run with arguments. - * + * * @return {@link Varargs} containing any values returned by mainChunk. */ public static Varargs luaMain(LuaValue mainChunk, String[] args) { diff --git a/luaj-jse/src/main/java/org/luaj/vm2/lib/jse/JseProcess.java b/luaj-jse/src/main/java/org/luaj/vm2/lib/jse/JseProcess.java index 42a5d528..337cf9ad 100644 --- a/luaj-jse/src/main/java/org/luaj/vm2/lib/jse/JseProcess.java +++ b/luaj-jse/src/main/java/org/luaj/vm2/lib/jse/JseProcess.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 @@ -36,7 +36,7 @@ public class JseProcess { /** * Construct a process around a command, with specified streams to redirect * input and output to. - * + * * @param cmd The command to execute, including arguments, if any * @param stdin Optional InputStream to read from as process input, or null * if input is not needed. @@ -54,7 +54,7 @@ public class JseProcess { /** * Construct a process around a command, with specified streams to redirect * input and output to. - * + * * @param cmd The command to execute, including arguments, if any * @param stdin Optional InputStream to read from as process input, or null * if input is not needed. @@ -83,7 +83,7 @@ public class JseProcess { /** * Wait for the process to complete, and all pending output to finish. - * + * * @return The exit status. * @throws InterruptedException */ @@ -102,7 +102,7 @@ public class JseProcess { /** Create a thread to copy bytes from input to output. */ private Thread copyBytes(final InputStream input, final OutputStream output, final InputStream ownedInput, final OutputStream ownedOutput) { - Thread t = (new CopyThread(output, ownedOutput, ownedInput, input)); + Thread t = new CopyThread(output, ownedOutput, ownedInput, input); t.start(); return t; } @@ -120,6 +120,7 @@ public class JseProcess { this.input = input; } + @Override public void run() { try { byte[] buf = new byte[1024]; diff --git a/luaj-jse/src/main/java/org/luaj/vm2/lib/jse/JseStringLib.java b/luaj-jse/src/main/java/org/luaj/vm2/lib/jse/JseStringLib.java index 87c9f097..3923b080 100644 --- a/luaj-jse/src/main/java/org/luaj/vm2/lib/jse/JseStringLib.java +++ b/luaj-jse/src/main/java/org/luaj/vm2/lib/jse/JseStringLib.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 @@ -27,10 +27,11 @@ public class JseStringLib extends org.luaj.vm2.lib.StringLib { public JseStringLib() { } + @Override protected String format(String src, double x) { String out; try { - out = String.format(src, new Object[] { Double.valueOf(x) }); + out = String.format(src, Double.valueOf(x)); } catch (Throwable e) { out = super.format(src, x); } diff --git a/luaj-jse/src/main/java/org/luaj/vm2/lib/jse/LuajavaLib.java b/luaj-jse/src/main/java/org/luaj/vm2/lib/jse/LuajavaLib.java index 53d46ccc..b7c0261b 100644 --- a/luaj-jse/src/main/java/org/luaj/vm2/lib/jse/LuajavaLib.java +++ b/luaj-jse/src/main/java/org/luaj/vm2/lib/jse/LuajavaLib.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 @@ -44,11 +44,11 @@ import org.luaj.vm2.lib.VarArgFunction; * bind java classes and methods to lua dynamically. The API is documented on * the luajava documentation * pages. - * + * *

    * Typically, this library is included as part of a call to * {@link org.luaj.vm2.lib.jse.JsePlatform#standardGlobals()} - * + * *

      * {
      * 	@code
    @@ -60,7 +60,7 @@ import org.luaj.vm2.lib.VarArgFunction;
      * 

    * To instantiate and use it directly, link it into your globals table via * {@link Globals#load} using code such as: - * + * *

      * {
      * 	@code
    @@ -73,7 +73,7 @@ import org.luaj.vm2.lib.VarArgFunction;
      * }
      * 
    *

    - * + * * The {@code luajava} library is available on all JSE platforms via the call to * {@link org.luaj.vm2.lib.jse.JsePlatform#standardGlobals()} and the luajava * api's are simply invoked from lua. Because it makes extensive use of Java's @@ -82,7 +82,7 @@ import org.luaj.vm2.lib.VarArgFunction; *

    * This has been implemented to match as closely as possible the behavior in the * corresponding library in C. - * + * * @see LibFunction * @see org.luaj.vm2.lib.jse.JsePlatform * @see org.luaj.vm2.lib.jme.JmePlatform @@ -108,6 +108,7 @@ public class LuajavaLib extends VarArgFunction { public LuajavaLib() { } + @Override public Varargs invoke(Varargs args) { try { switch (opcode) { @@ -129,8 +130,8 @@ public class LuajavaLib extends VarArgFunction { case NEW: { // get constructor final LuaValue c = args.checkvalue(1); - final Class clazz = (opcode == NEWINSTANCE? classForName(c.tojstring()) - : (Class) c.checkuserdata(Class.class)); + final Class clazz = opcode == NEWINSTANCE? classForName(c.tojstring()) + : (Class) c.checkuserdata(Class.class); final Varargs consargs = args.subargs(2); return JavaClass.forClass(clazz).getConstructor().invoke(consargs); } @@ -160,8 +161,8 @@ public class LuajavaLib extends VarArgFunction { String classname = args.checkjstring(1); String methodname = args.checkjstring(2); Class clazz = classForName(classname); - Method method = clazz.getMethod(methodname, new Class[] {}); - Object result = method.invoke(clazz, new Object[] {}); + Method method = clazz.getMethod(methodname); + Object result = method.invoke(clazz); if (result instanceof LuaValue) { return (LuaValue) result; } else { @@ -192,12 +193,13 @@ public class LuajavaLib extends VarArgFunction { this.lobj = lobj; } + @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { String name = method.getName(); LuaValue func = lobj.get(name); if (func.isnil()) return null; - boolean isvarargs = ((method.getModifiers() & METHOD_MODIFIERS_VARARGS) != 0); + boolean isvarargs = (method.getModifiers() & METHOD_MODIFIERS_VARARGS) != 0; int n = args != null? args.length: 0; LuaValue[] v; if (isvarargs) { diff --git a/luaj-jse/src/main/java/org/luaj/vm2/luajc/BasicBlock.java b/luaj-jse/src/main/java/org/luaj/vm2/luajc/BasicBlock.java index ec74ae0e..e42374d8 100644 --- a/luaj-jse/src/main/java/org/luaj/vm2/luajc/BasicBlock.java +++ b/luaj-jse/src/main/java/org/luaj/vm2/luajc/BasicBlock.java @@ -1,5 +1,5 @@ /** - * + * */ package org.luaj.vm2.luajc; @@ -18,9 +18,10 @@ public class BasicBlock { this.pc0 = this.pc1 = pc0; } + @Override public String toString() { StringBuffer sb = new StringBuffer(); - sb.append((pc0+1) + "-" + (pc1+1) + (prev != null? " prv: " + str(prev, 1): "") + sb.append(pc0 + 1 + "-" + (pc1+1) + (prev != null? " prv: " + str(prev, 1): "") + (next != null? " nxt: " + str(next, 0): "") + "\n"); return sb.toString(); } @@ -82,6 +83,7 @@ public class BasicBlock { this.blocks = blocks; } + @Override public void visitBranch(int pc0, int pc1) { if (blocks[pc0].next == null) blocks[pc0].next = new BasicBlock[nnext[pc0]]; @@ -102,6 +104,7 @@ public class BasicBlock { this.nprev = nprev; } + @Override public void visitBranch(int pc0, int pc1) { nnext[pc0]++; nprev[pc1]++; @@ -116,11 +119,13 @@ public class BasicBlock { this.isend = isend; } + @Override public void visitBranch(int pc0, int pc1) { isend[pc0] = true; isbeg[pc1] = true; } + @Override public void visitReturn(int pc) { isend[pc] = true; } diff --git a/luaj-jse/src/main/java/org/luaj/vm2/luajc/JavaBuilder.java b/luaj-jse/src/main/java/org/luaj/vm2/luajc/JavaBuilder.java index 07719c2b..b08189eb 100644 --- a/luaj-jse/src/main/java/org/luaj/vm2/luajc/JavaBuilder.java +++ b/luaj-jse/src/main/java/org/luaj/vm2/luajc/JavaBuilder.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 @@ -177,11 +177,9 @@ public class JavaBuilder { superclassType = p.numparams; if (p.is_vararg != 0 || superclassType >= SUPERTYPE_VARARGS) superclassType = SUPERTYPE_VARARGS; - for (int i = 0, n = p.code.length; i < n; i++) { - int inst = p.code[i]; + for (int inst : p.code) { int o = Lua.GET_OPCODE(inst); - if ((o == Lua.OP_TAILCALL) - || ((o == Lua.OP_RETURN) && (Lua.GETARG_B(inst) < 1 || Lua.GETARG_B(inst) > 2))) { + if (o == Lua.OP_TAILCALL || o == Lua.OP_RETURN && (Lua.GETARG_B(inst) < 1 || Lua.GETARG_B(inst) > 2)) { superclassType = SUPERTYPE_VARARGS; break; } @@ -244,7 +242,7 @@ public class JavaBuilder { } else { // fixed arg function between 0 and 3 arguments for (slot = 0; slot < p.numparams; slot++) { - this.plainSlotVars.put(Integer.valueOf(slot), Integer.valueOf(1+slot)); + this.plainSlotVars.put(slot, 1+slot); if (pi.isUpvalueCreate(-1, slot)) { append(new ALOAD(1+slot)); storeLocal(-1, slot); @@ -252,7 +250,7 @@ public class JavaBuilder { } } - // nil parameters + // nil parameters // TODO: remove this for lua 5.2, not needed for (; slot < p.maxstacksize; slot++) { if (pi.isInitialValueUsed(slot)) { @@ -264,7 +262,7 @@ public class JavaBuilder { public byte[] completeClass(boolean genmain) { - // add class initializer + // add class initializer if (!init.isEmpty()) { MethodGen mg = new MethodGen(Constants.ACC_STATIC, Type.VOID, ARG_TYPES_NONE, new String[] {}, "", cg.getClassName(), init, cg.getConstantPool()); @@ -283,7 +281,7 @@ public class JavaBuilder { cg.addMethod(mg.getMethod()); main.dispose(); - // add initupvalue1(LuaValue env) to initialize environment for main chunk + // add initupvalue1(LuaValue env) to initialize environment for main chunk if (p.upvalues.length == 1 && superclassType == SUPERTYPE_VARARGS) { MethodGen mg = new MethodGen(Constants.ACC_PUBLIC | Constants.ACC_FINAL, // access flags Type.VOID, // return type @@ -307,7 +305,7 @@ public class JavaBuilder { main.dispose(); } - // add main function so class is invokable from the java command line + // add main function so class is invokable from the java command line if (genmain) { MethodGen mg = new MethodGen(Constants.ACC_PUBLIC | Constants.ACC_STATIC, // access flags Type.VOID, // return type @@ -355,22 +353,22 @@ public class JavaBuilder { } public void loadBoolean(boolean b) { - String field = (b? "TRUE": "FALSE"); + String field = b? "TRUE": "FALSE"; append(factory.createFieldAccess(STR_LUAVALUE, field, TYPE_LUABOOLEAN, Constants.GETSTATIC)); } - private Map plainSlotVars = new HashMap(); - private Map upvalueSlotVars = new HashMap(); - private Map localVarGenBySlot = new HashMap(); + private final Map plainSlotVars = new HashMap<>(); + private final Map upvalueSlotVars = new HashMap<>(); + private final Map localVarGenBySlot = new HashMap<>(); private int findSlot(int slot, Map map, String prefix, Type type) { - Integer islot = Integer.valueOf(slot); + Integer islot = slot; if (map.containsKey(islot)) - return ((Integer) map.get(islot)).intValue(); + return map.get(islot).intValue(); String name = prefix+slot; LocalVariableGen local = mg.addLocalVariable(name, type, null, null); int index = local.getIndex(); - map.put(islot, Integer.valueOf(index)); + map.put(islot, index); localVarGenBySlot.put(islot, local); return index; } @@ -727,7 +725,7 @@ public class JavaBuilder { append(factory.createFieldAccess(protoname, destname, uptype, Constants.PUTFIELD)); } - private Map constants = new HashMap(); + private final Map constants = new HashMap<>(); public void loadConstant(LuaValue value) { switch (value.type()) { @@ -739,7 +737,7 @@ public class JavaBuilder { break; case LuaValue.TNUMBER: case LuaValue.TSTRING: - String name = (String) constants.get(value); + String name = constants.get(value); if (name == null) { name = value.type() == LuaValue.TNUMBER? value.isinttype()? createLuaIntegerField(value.checkint()) : createLuaDoubleField(value.checkdouble()): createLuaStringField(value.checkstring()); @@ -786,7 +784,7 @@ public class JavaBuilder { } else { char[] c = new char[ls.m_length]; for (int j = 0; j < ls.m_length; j++) - c[j] = (char) (0xff & (int) (ls.m_bytes[ls.m_offset+j])); + c[j] = (char) (0xff & ls.m_bytes[ls.m_offset+j]); init.append(new PUSH(cp, new String(c))); init.append( factory.createInvoke(STR_STRING, "toCharArray", TYPE_CHARARRAY, Type.NO_ARGS, Constants.INVOKEVIRTUAL)); @@ -845,10 +843,10 @@ public class JavaBuilder { } public void setVarStartEnd(int slot, int start_pc, int end_pc, String name) { - Integer islot = Integer.valueOf(slot); + Integer islot = slot; if (localVarGenBySlot.containsKey(islot)) { name = name.replaceAll("[^a-zA-Z0-9]", "_"); - LocalVariableGen l = (LocalVariableGen) localVarGenBySlot.get(islot); + LocalVariableGen l = localVarGenBySlot.get(islot); l.setEnd(lastInstrHandles[end_pc-1]); if (start_pc > 1) l.setStart(lastInstrHandles[start_pc-2]); @@ -908,7 +906,7 @@ public class JavaBuilder { public void closeUpvalue(int pc, int upindex) { // TODO: assign the upvalue location the value null; /* - boolean isrw = pi.isReadWriteUpvalue( pi.upvals[upindex] ); + boolean isrw = pi.isReadWriteUpvalue( pi.upvals[upindex] ); append(InstructionConstants.THIS); append(InstructionConstants.ACONST_NULL); if ( isrw ) { diff --git a/luaj-jse/src/main/java/org/luaj/vm2/luajc/JavaGen.java b/luaj-jse/src/main/java/org/luaj/vm2/luajc/JavaGen.java index 53f571d4..db016d14 100644 --- a/luaj-jse/src/main/java/org/luaj/vm2/luajc/JavaGen.java +++ b/luaj-jse/src/main/java/org/luaj/vm2/luajc/JavaGen.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 @@ -66,9 +66,7 @@ public class JavaGen { Prototype p = pi.prototype; int vresultbase = -1; - for (int bi = 0; bi < pi.blocklist.length; bi++) { - BasicBlock b0 = pi.blocklist[bi]; - + for (BasicBlock b0 : pi.blocklist) { // convert upvalues that are phi-variables for (int slot = 0; slot < p.maxstacksize; slot++) { int pc = b0.pc0; @@ -216,19 +214,19 @@ public class JavaGen { loadLocalOrConstant(p, builder, pc, b); loadLocalOrConstant(p, builder, pc, c); builder.compareop(o); - builder.addBranch(pc, (a != 0? JavaBuilder.BRANCH_IFEQ: JavaBuilder.BRANCH_IFNE), pc+2); + builder.addBranch(pc, a != 0? JavaBuilder.BRANCH_IFEQ: JavaBuilder.BRANCH_IFNE, pc+2); break; case Lua.OP_TEST: /* A C if not (R(A) <=> C) then pc++ */ builder.loadLocal(pc, a); builder.toBoolean(); - builder.addBranch(pc, (c != 0? JavaBuilder.BRANCH_IFEQ: JavaBuilder.BRANCH_IFNE), pc+2); + builder.addBranch(pc, c != 0? JavaBuilder.BRANCH_IFEQ: JavaBuilder.BRANCH_IFNE, pc+2); break; case Lua.OP_TESTSET: /* A B C if (R(B) <=> C) then R(A):= R(B) else pc++ */ builder.loadLocal(pc, b); builder.toBoolean(); - builder.addBranch(pc, (c != 0? JavaBuilder.BRANCH_IFEQ: JavaBuilder.BRANCH_IFNE), pc+2); + builder.addBranch(pc, c != 0? JavaBuilder.BRANCH_IFEQ: JavaBuilder.BRANCH_IFNE, pc+2); builder.loadLocal(pc, b); builder.storeLocal(pc, a); break; diff --git a/luaj-jse/src/main/java/org/luaj/vm2/luajc/JavaLoader.java b/luaj-jse/src/main/java/org/luaj/vm2/luajc/JavaLoader.java index 42229c30..ed8caf42 100644 --- a/luaj-jse/src/main/java/org/luaj/vm2/luajc/JavaLoader.java +++ b/luaj-jse/src/main/java/org/luaj/vm2/luajc/JavaLoader.java @@ -19,7 +19,7 @@ import org.luaj.vm2.Prototype; * * 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 @@ -30,7 +30,7 @@ import org.luaj.vm2.Prototype; ******************************************************************************/ public class JavaLoader extends ClassLoader { - private Map unloaded = new HashMap(); + private final Map unloaded = new HashMap<>(); public JavaLoader() { } @@ -63,8 +63,9 @@ public class JavaLoader extends ClassLoader { include(jg.inners[i]); } + @Override public Class findClass(String classname) throws ClassNotFoundException { - byte[] bytes = (byte[]) unloaded.get(classname); + byte[] bytes = unloaded.get(classname); if (bytes != null) return defineClass(classname, bytes, 0, bytes.length); return super.findClass(classname); diff --git a/luaj-jse/src/main/java/org/luaj/vm2/luajc/LuaJC.java b/luaj-jse/src/main/java/org/luaj/vm2/luajc/LuaJC.java index 9346aa2f..9fd694b6 100644 --- a/luaj-jse/src/main/java/org/luaj/vm2/luajc/LuaJC.java +++ b/luaj-jse/src/main/java/org/luaj/vm2/luajc/LuaJC.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 @@ -44,7 +44,7 @@ import org.luaj.vm2.compiler.LuaC; *

    * To override the default compiling behavior with {@link LuaJC} lua-to-java * bytecode compiler, install it before undumping code, for example: - * + * *

      *  {@code
      * LuaValue globals = JsePlatform.standardGlobals();
    @@ -58,7 +58,7 @@ import org.luaj.vm2.compiler.LuaC;
      * This requires the bcel library to be on the class path to work as expected.
      * If the library is not found, the default {@link LuaC} lua-to-lua-bytecode
      * compiler will be used.
    - * 
    + *
      * @see Globals#compiler
      * @see #install(Globals)
      * @see org.luaj.vm2.compiler.LuaC
    @@ -107,6 +107,7 @@ public class LuaJC implements Globals.Loader {
     			insert(h, gen.inners[i]);
     	}
     
    +	@Override
     	public LuaFunction load(Prototype p, String name, LuaValue globals) throws IOException {
     		String luaname = toStandardLuaFileName(name);
     		String classname = toStandardJavaClassName(luaname);
    @@ -120,8 +121,7 @@ public class LuaJC implements Globals.Loader {
     		for (int i = 0, n = stub.length(); i < n; ++i) {
     			final char c = stub.charAt(i);
     			classname.append(
    -				(((i == 0) && Character.isJavaIdentifierStart(c)) || ((i > 0) && Character.isJavaIdentifierPart(c)))? c
    -					: '_');
    +				i == 0 && Character.isJavaIdentifierStart(c) || i > 0 && Character.isJavaIdentifierPart(c)? c: '_');
     		}
     		return classname.toString();
     	}
    @@ -133,7 +133,6 @@ public class LuaJC implements Globals.Loader {
     	}
     
     	private static String toStub(String s) {
    -		String stub = s.endsWith(".lua")? s.substring(0, s.length()-4): s;
    -		return stub;
    +		return s.endsWith(".lua")? s.substring(0, s.length()-4): s;
     	}
     }
    diff --git a/luaj-jse/src/main/java/org/luaj/vm2/luajc/ProtoInfo.java b/luaj-jse/src/main/java/org/luaj/vm2/luajc/ProtoInfo.java
    index fa302979..c34c8586 100644
    --- a/luaj-jse/src/main/java/org/luaj/vm2/luajc/ProtoInfo.java
    +++ b/luaj-jse/src/main/java/org/luaj/vm2/luajc/ProtoInfo.java
    @@ -57,6 +57,7 @@ public class ProtoInfo {
     		findUpvalues();
     	}
     
    +	@Override
     	public String toString() {
     		StringBuffer sb = new StringBuffer();
     
    @@ -64,12 +65,11 @@ public class ProtoInfo {
     		sb.append("proto '" + name + "'\n");
     
     		// upvalues from outer scopes
    -		for (int i = 0, n = (upvals != null? upvals.length: 0); i < n; i++)
    +		for (int i = 0, n = upvals != null? upvals.length: 0; i < n; i++)
     			sb.append(" up[" + i + "]: " + upvals[i] + "\n");
     
     		// basic blocks
    -		for (int i = 0; i < blocklist.length; i++) {
    -			BasicBlock b = blocklist[i];
    +		for (BasicBlock b : blocklist) {
     			int pc0 = b.pc0;
     			sb.append("  block " + b.toString());
     			appendOpenUps(sb, -1);
    @@ -84,9 +84,9 @@ public class ProtoInfo {
     				sb.append("     ");
     				for (int j = 0; j < prototype.maxstacksize; j++) {
     					VarInfo v = vars[j][pc];
    -					String u = (v == null? ""
    -						: v.upvalue != null? !v.upvalue.rw? "[C] ": (v.allocupvalue && v.pc == pc? "[*] ": "[]  ")
    -							: "    ");
    +					String u = v == null? ""
    +						: v.upvalue != null? !v.upvalue.rw? "[C] ": v.allocupvalue && v.pc == pc? "[*] ": "[]  "
    +							: "    ";
     					String s = v == null? "null   ": String.valueOf(v);
     					sb.append(s+u);
     				}
    @@ -115,7 +115,7 @@ public class ProtoInfo {
     
     	private void appendOpenUps(StringBuffer sb, int pc) {
     		for (int j = 0; j < prototype.maxstacksize; j++) {
    -			VarInfo v = (pc < 0? params[j]: vars[j][pc]);
    +			VarInfo v = pc < 0? params[j]: vars[j][pc];
     			if (v != null && v.pc == pc && v.allocupvalue) {
     				sb.append("    open: " + v.upvalue + "\n");
     			}
    @@ -132,8 +132,8 @@ public class ProtoInfo {
     			v[i] = new VarInfo[n];
     
     		// process instructions
    -		for (int bi = 0; bi < blocklist.length; bi++) {
    -			BasicBlock b0 = blocklist[bi];
    +		for (BasicBlock element : blocklist) {
    +			BasicBlock b0 = element;
     
     			// input from previous blocks
     			int nprev = b0.prev != null? b0.prev.length: 0;
    @@ -399,8 +399,7 @@ public class ProtoInfo {
     	}
     
     	private void replaceTrivialPhiVariables() {
    -		for (int i = 0; i < blocklist.length; i++) {
    -			BasicBlock b0 = blocklist[i];
    +		for (BasicBlock b0 : blocklist) {
     			for (int slot = 0; slot < prototype.maxstacksize; slot++) {
     				VarInfo vold = vars[slot][b0.pc0];
     				VarInfo vnew = vold.resolvePhiVariableValues();
    diff --git a/luaj-jse/src/main/java/org/luaj/vm2/luajc/UpvalInfo.java b/luaj-jse/src/main/java/org/luaj/vm2/luajc/UpvalInfo.java
    index 7d331c75..b27aaa8f 100644
    --- a/luaj-jse/src/main/java/org/luaj/vm2/luajc/UpvalInfo.java
    +++ b/luaj-jse/src/main/java/org/luaj/vm2/luajc/UpvalInfo.java
    @@ -1,5 +1,5 @@
     /**
    - * 
    + *
      */
     package org.luaj.vm2.luajc;
     
    @@ -60,8 +60,7 @@ public class UpvalInfo {
     
     	private boolean includePosteriorVarsCheckLoops(VarInfo prior) {
     		boolean loopDetected = false;
    -		for (int i = 0, n = pi.blocklist.length; i < n; i++) {
    -			BasicBlock b = pi.blocklist[i];
    +		for (BasicBlock b : pi.blocklist) {
     			VarInfo v = pi.vars[slot][b.pc1];
     			if (v == prior) {
     				for (int j = 0, m = b.next != null? b.next.length: 0; j < m; j++) {
    @@ -86,8 +85,7 @@ public class UpvalInfo {
     	}
     
     	private void includePriorVarsIgnoreLoops(VarInfo poster) {
    -		for (int i = 0, n = pi.blocklist.length; i < n; i++) {
    -			BasicBlock b = pi.blocklist[i];
    +		for (BasicBlock b : pi.blocklist) {
     			VarInfo v = pi.vars[slot][b.pc0];
     			if (v == poster) {
     				for (int j = 0, m = b.prev != null? b.prev.length: 0; j < m; j++) {
    @@ -118,6 +116,7 @@ public class UpvalInfo {
     		var[nvars++] = v;
     	}
     
    +	@Override
     	public String toString() {
     		StringBuffer sb = new StringBuffer();
     		sb.append(pi.name);
    @@ -141,8 +140,8 @@ public class UpvalInfo {
     			if (v != null && v.upvalue != this)
     				return true;
     		} else {
    -			for (int i = 0, n = b.prev.length; i < n; i++) {
    -				v = pi.vars[slot][b.prev[i].pc1];
    +			for (BasicBlock element : b.prev) {
    +				v = pi.vars[slot][element.pc1];
     				if (v != null && v.upvalue != this)
     					return true;
     			}
    diff --git a/luaj-jse/src/main/java/org/luaj/vm2/luajc/VarInfo.java b/luaj-jse/src/main/java/org/luaj/vm2/luajc/VarInfo.java
    index ee326d91..00f7c460 100644
    --- a/luaj-jse/src/main/java/org/luaj/vm2/luajc/VarInfo.java
    +++ b/luaj-jse/src/main/java/org/luaj/vm2/luajc/VarInfo.java
    @@ -1,5 +1,5 @@
     /**
    - * 
    + *
      */
     package org.luaj.vm2.luajc;
     
    @@ -37,15 +37,16 @@ public class VarInfo {
     		this.pc = pc;
     	}
     
    +	@Override
     	public String toString() {
    -		return slot < 0? "x.x": (slot + "." + pc);
    +		return slot < 0? "x.x": slot + "." + pc;
     	}
     
     	/**
     	 * Return replacement variable if there is exactly one value possible,
     	 * otherwise compute entire collection of variables and return null.
     	 * Computes the list of aall variable values, and saves it for the future.
    -	 * 
    +	 *
     	 * @return new Variable to replace with if there is only one value, or null
     	 *         to leave alone.
     	 */
    @@ -64,6 +65,7 @@ public class VarInfo {
     			super(slot, pc);
     		}
     
    +		@Override
     		public String toString() {
     			return slot + ".p";
     		}
    @@ -74,6 +76,7 @@ public class VarInfo {
     			super(slot, pc);
     		}
     
    +		@Override
     		public String toString() {
     			return "nil";
     		}
    @@ -88,13 +91,15 @@ public class VarInfo {
     			this.pi = pi;
     		}
     
    +		@Override
     		public boolean isPhiVar() { return true; }
     
    +		@Override
     		public String toString() {
     			StringBuffer sb = new StringBuffer();
     			sb.append(super.toString());
     			sb.append("={");
    -			for (int i = 0, n = (values != null? values.length: 0); i < n; i++) {
    +			for (int i = 0, n = values != null? values.length: 0; i < n; i++) {
     				if (i > 0)
     					sb.append(",");
     				sb.append(String.valueOf(values[i]));
    @@ -103,6 +108,7 @@ public class VarInfo {
     			return sb.toString();
     		}
     
    +		@Override
     		public VarInfo resolvePhiVariableValues() {
     			Set visitedBlocks = new HashSet();
     			Set vars = new HashSet();
    @@ -124,6 +130,7 @@ public class VarInfo {
     			return null;
     		}
     
    +		@Override
     		protected void collectUniqueValues(Set visitedBlocks, Set vars) {
     			BasicBlock b = pi.blocks[pc];
     			if (pc == 0)
    diff --git a/luaj-jse/src/main/java/org/luaj/vm2/script/LuaScriptEngine.java b/luaj-jse/src/main/java/org/luaj/vm2/script/LuaScriptEngine.java
    index 154306d4..995ec2ee 100644
    --- a/luaj-jse/src/main/java/org/luaj/vm2/script/LuaScriptEngine.java
    +++ b/luaj-jse/src/main/java/org/luaj/vm2/script/LuaScriptEngine.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,11 +21,29 @@
     ******************************************************************************/
     package org.luaj.vm2.script;
     
    -import java.io.*;
    +import java.io.IOException;
    +import java.io.InputStream;
    +import java.io.Reader;
    +import java.io.StringReader;
     
    -import javax.script.*;
    +import javax.script.AbstractScriptEngine;
    +import javax.script.Bindings;
    +import javax.script.Compilable;
    +import javax.script.CompiledScript;
    +import javax.script.ScriptContext;
    +import javax.script.ScriptEngine;
    +import javax.script.ScriptEngineFactory;
    +import javax.script.ScriptException;
    +import javax.script.SimpleBindings;
     
    -import org.luaj.vm2.*;
    +import org.luaj.vm2.Globals;
    +import org.luaj.vm2.Lua;
    +import org.luaj.vm2.LuaClosure;
    +import org.luaj.vm2.LuaError;
    +import org.luaj.vm2.LuaFunction;
    +import org.luaj.vm2.LuaTable;
    +import org.luaj.vm2.LuaValue;
    +import org.luaj.vm2.Varargs;
     import org.luaj.vm2.lib.ThreeArgFunction;
     import org.luaj.vm2.lib.TwoArgFunction;
     import org.luaj.vm2.lib.jse.CoerceJavaToLua;
    @@ -33,7 +51,7 @@ import org.luaj.vm2.lib.jse.CoerceJavaToLua;
     /**
      * Implementation of the ScriptEngine interface which can compile and execute
      * scripts using luaj.
    - * 
    + *
      * 

    * This engine requires the types of the Bindings and ScriptContext to be * compatible with the engine. For creating new client context use @@ -53,7 +71,7 @@ public class LuaScriptEngine extends AbstractScriptEngine implements ScriptEngin private static final ScriptEngineFactory myFactory = new LuaScriptEngineFactory(); - private LuajContext context; + private final LuajContext context; public LuaScriptEngine() { // set up context @@ -80,15 +98,12 @@ public class LuaScriptEngine extends AbstractScriptEngine implements ScriptEngin @Override public CompiledScript compile(Reader script) throws ScriptException { try { - InputStream is = new Utf8Encoder(script); - try { + try (InputStream is = new Utf8Encoder(script)) { final Globals g = context.globals; final LuaFunction f = g.load(script, "script").checkfunction(); return new LuajCompiledScript(f, g); } catch (LuaError lee) { throw new ScriptException(lee.getMessage()); - } finally { - is.close(); } } catch (Exception e) { throw new ScriptException("eval threw " + e.toString()); @@ -137,16 +152,20 @@ public class LuaScriptEngine extends AbstractScriptEngine implements ScriptEngin this.compiling_globals = compiling_globals; } + @Override public ScriptEngine getEngine() { return LuaScriptEngine.this; } + @Override public Object eval() throws ScriptException { return eval(getContext()); } + @Override public Object eval(Bindings bindings) throws ScriptException { return eval(((LuajContext) getContext()).globals, bindings); } + @Override public Object eval(ScriptContext context) throws ScriptException { return eval(((LuajContext) context).globals, context.getBindings(ScriptContext.ENGINE_SCOPE)); } @@ -168,7 +187,7 @@ public class LuaScriptEngine extends AbstractScriptEngine implements ScriptEngin } } - // ------ convert char stream to byte stream for lua compiler ----- + // ------ convert char stream to byte stream for lua compiler ----- private final class Utf8Encoder extends InputStream { private final Reader r; @@ -179,6 +198,7 @@ public class LuaScriptEngine extends AbstractScriptEngine implements ScriptEngin this.r = r; } + @Override public int read() throws IOException { if (n > 0) return buf[--n]; @@ -187,12 +207,12 @@ public class LuaScriptEngine extends AbstractScriptEngine implements ScriptEngin return c; n = 0; if (c < 0x800) { - buf[n++] = (0x80 | (c & 0x3f)); - return (0xC0 | ((c>>6) & 0x1f)); + buf[n++] = 0x80 | c & 0x3f; + return 0xC0 | c>>6 & 0x1f; } else { - buf[n++] = (0x80 | (c & 0x3f)); - buf[n++] = (0x80 | ((c>>6) & 0x3f)); - return (0xE0 | ((c>>12) & 0x0f)); + buf[n++] = 0x80 | c & 0x3f; + buf[n++] = 0x80 | c>>6 & 0x3f; + return 0xE0 | c>>12 & 0x0f; } } } @@ -201,6 +221,7 @@ public class LuaScriptEngine extends AbstractScriptEngine implements ScriptEngin BindingsMetatable(final Bindings bindings) { this.rawset(LuaValue.INDEX, new TwoArgFunction() { + @Override public LuaValue call(LuaValue table, LuaValue key) { if (key.isstring()) return toLua(bindings.get(key.tojstring())); @@ -209,6 +230,7 @@ public class LuaScriptEngine extends AbstractScriptEngine implements ScriptEngin } }); this.rawset(LuaValue.NEWINDEX, new ThreeArgFunction() { + @Override public LuaValue call(LuaValue table, LuaValue key, LuaValue value) { if (key.isstring()) { final String k = key.tojstring(); @@ -240,8 +262,8 @@ public class LuaScriptEngine extends AbstractScriptEngine implements ScriptEngin case LuaValue.TUSERDATA: return luajValue.checkuserdata(Object.class); case LuaValue.TNUMBER: - return luajValue.isinttype()? (Object) new Integer(luajValue.toint()) - : (Object) new Double(luajValue.todouble()); + return luajValue.isinttype()? (Object) Integer.valueOf(luajValue.toint()) + : (Object) Double.valueOf(luajValue.todouble()); default: return luajValue; } diff --git a/luaj-jse/src/main/java/org/luaj/vm2/script/LuaScriptEngineFactory.java b/luaj-jse/src/main/java/org/luaj/vm2/script/LuaScriptEngineFactory.java index a9760908..2027b476 100644 --- a/luaj-jse/src/main/java/org/luaj/vm2/script/LuaScriptEngineFactory.java +++ b/luaj-jse/src/main/java/org/luaj/vm2/script/LuaScriptEngineFactory.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 @@ -29,7 +29,7 @@ import javax.script.ScriptEngineFactory; /** * Jsr 223 scripting engine factory. - * + * * Exposes metadata to support the lua language, and constructs instances of * LuaScriptEngine to handl lua scripts. */ @@ -41,9 +41,9 @@ public class LuaScriptEngineFactory implements ScriptEngineFactory { private static final String[] NAMES = { "lua", "luaj", }; - private List extensions; - private List mimeTypes; - private List names; + private final List extensions; + private final List mimeTypes; + private final List names; public LuaScriptEngineFactory() { extensions = Arrays.asList(EXTENSIONS); @@ -51,24 +51,33 @@ public class LuaScriptEngineFactory implements ScriptEngineFactory { names = Arrays.asList(NAMES); } + @Override public String getEngineName() { return getScriptEngine().get(ScriptEngine.ENGINE).toString(); } + @Override public String getEngineVersion() { return getScriptEngine().get(ScriptEngine.ENGINE_VERSION).toString(); } + @Override public List getExtensions() { return extensions; } + @Override public List getMimeTypes() { return mimeTypes; } + @Override public List getNames() { return names; } + @Override public String getLanguageName() { return getScriptEngine().get(ScriptEngine.LANGUAGE).toString(); } + @Override public String getLanguageVersion() { return getScriptEngine().get(ScriptEngine.LANGUAGE_VERSION).toString(); } + @Override public Object getParameter(String key) { return getScriptEngine().get(key).toString(); } + @Override public String getMethodCallSyntax(String obj, String m, String... args) { StringBuffer sb = new StringBuffer(); sb.append(obj + ":" + m + "("); @@ -83,10 +92,12 @@ public class LuaScriptEngineFactory implements ScriptEngineFactory { return sb.toString(); } + @Override public String getOutputStatement(String toDisplay) { return "print(" + toDisplay + ")"; } + @Override public String getProgram(String... statements) { StringBuffer sb = new StringBuffer(); int len = statements.length; @@ -99,5 +110,6 @@ public class LuaScriptEngineFactory implements ScriptEngineFactory { return sb.toString(); } + @Override public ScriptEngine getScriptEngine() { return new LuaScriptEngine(); } } diff --git a/luaj-jse/src/main/java/org/luaj/vm2/script/LuajContext.java b/luaj-jse/src/main/java/org/luaj/vm2/script/LuajContext.java index 417caa8d..038dd867 100644 --- a/luaj-jse/src/main/java/org/luaj/vm2/script/LuajContext.java +++ b/luaj-jse/src/main/java/org/luaj/vm2/script/LuajContext.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 @@ -71,7 +71,7 @@ public class LuajContext extends SimpleScriptContext implements ScriptContext { * If createDebugGlobals is set, the globals created will be a debug globals * that includes the debug library. This may provide better stack traces, * but may have negative impact on performance. - * + * * @param createDebugGlobals true to create debug globals, false for * standard globals. * @param useLuaJCCompiler true to use the luajc compiler, reqwuires bcel @@ -106,22 +106,27 @@ public class LuajContext extends SimpleScriptContext implements ScriptContext { this.w = w; } + @Override public void write(int b) throws IOException { w.write(new String(new byte[] { (byte) b })); } + @Override public void write(byte[] b, int o, int l) throws IOException { w.write(new String(b, o, l)); } + @Override public void write(byte[] b) throws IOException { w.write(new String(b)); } + @Override public void close() throws IOException { w.close(); } + @Override public void flush() throws IOException { w.flush(); } @@ -134,6 +139,7 @@ public class LuajContext extends SimpleScriptContext implements ScriptContext { this.r = r; } + @Override public int read() throws IOException { return r.read(); } diff --git a/luaj-jse/src/main/java/org/luaj/vm2/server/DefaultLauncher.java b/luaj-jse/src/main/java/org/luaj/vm2/server/DefaultLauncher.java index 73e0491b..cebf12b8 100644 --- a/luaj-jse/src/main/java/org/luaj/vm2/server/DefaultLauncher.java +++ b/luaj-jse/src/main/java/org/luaj/vm2/server/DefaultLauncher.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 @@ -38,7 +38,7 @@ import org.luaj.vm2.lib.jse.JsePlatform; *

    * Return values with simple types are coerced into Java simple types. Tables, * threads, and functions are returned as lua objects. - * + * * @see Launcher * @see LuajClassLoader * @see LuajClassLoader#NewLauncher() @@ -53,6 +53,7 @@ public class DefaultLauncher implements Launcher { } /** Launches the script with chunk name 'main' */ + @Override public Object[] launch(String script, Object[] arg) { return launchChunk(g.load(script, "main"), arg); } @@ -60,11 +61,13 @@ public class DefaultLauncher implements Launcher { /** * Launches the script with chunk name 'main' and loading using modes 'bt' */ + @Override public Object[] launch(InputStream script, Object[] arg) { return launchChunk(g.load(script, "main", "bt", g), arg); } /** Launches the script with chunk name 'main' */ + @Override public Object[] launch(Reader script, Object[] arg) { return launchChunk(g.load(script, "main"), arg); } diff --git a/luaj-jse/src/main/java/org/luaj/vm2/server/Launcher.java b/luaj-jse/src/main/java/org/luaj/vm2/server/Launcher.java index 3d236be6..1707e55e 100644 --- a/luaj-jse/src/main/java/org/luaj/vm2/server/Launcher.java +++ b/luaj-jse/src/main/java/org/luaj/vm2/server/Launcher.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 @@ -49,28 +49,28 @@ public interface Launcher { /** * Launch a script contained in a String. - * + * * @param script The script contents. * @param arg Optional arguments supplied to the script. * @return return values from the script. */ - public Object[] launch(String script, Object[] arg); + Object[] launch(String script, Object[] arg); /** * Launch a script from an InputStream. - * + * * @param script The script as an InputStream. * @param arg Optional arguments supplied to the script. * @return return values from the script. */ - public Object[] launch(InputStream script, Object[] arg); + Object[] launch(InputStream script, Object[] arg); /** * Launch a script from a Reader. - * + * * @param script The script as a Reader. * @param arg Optional arguments supplied to the script. * @return return values from the script. */ - public Object[] launch(Reader script, Object[] arg); + Object[] launch(Reader script, Object[] arg); } diff --git a/luaj-jse/src/main/java/org/luaj/vm2/server/LuajClassLoader.java b/luaj-jse/src/main/java/org/luaj/vm2/server/LuajClassLoader.java index 4e3d75d6..6db51243 100644 --- a/luaj-jse/src/main/java/org/luaj/vm2/server/LuajClassLoader.java +++ b/luaj-jse/src/main/java/org/luaj/vm2/server/LuajClassLoader.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 @@ -52,7 +52,7 @@ import java.util.Map; * and prints the return values. This behavior can be changed by supplying a * different implementation class to {@link #NewLauncher(Class)} which must * extend {@link Launcher}. - * + * * @see Launcher * @see #NewLauncher() * @see #NewLauncher(Class) @@ -72,7 +72,7 @@ public class LuajClassLoader extends ClassLoader { static final String launcherInterfaceRoot = Launcher.class.getName(); /** Local cache of classes loaded by this loader. */ - Map> classes = new HashMap>(); + Map> classes = new HashMap<>(); /** * Construct a default {@link Launcher} instance that will load classes in @@ -83,7 +83,7 @@ public class LuajClassLoader extends ClassLoader { * classes are loaded into this loader including static variables such as * shared metatables, and should not be able to directly access variables * from other Launcher instances. - * + * * @return {@link Launcher} instance that can be used to launch scripts. * @throws InstantiationException * @throws IllegalAccessException @@ -102,7 +102,7 @@ public class LuajClassLoader extends ClassLoader { * classes are loaded into this loader including static variables such as * shared metatables, and should not be able to directly access variables * from other Launcher instances. - * + * * @return instance of type 'launcher_class' that can be used to launch * scripts. * @throws InstantiationException @@ -119,7 +119,7 @@ public class LuajClassLoader extends ClassLoader { /** * Test if a class name should be considered a user class and loaded by this * loader, or a system class and loaded by the system loader. - * + * * @param classname Class name to test. * @return true if this should be loaded into this class loader. */ @@ -127,6 +127,7 @@ public class LuajClassLoader extends ClassLoader { return classname.startsWith(luajPackageRoot) && !classname.startsWith(launcherInterfaceRoot); } + @Override public Class loadClass(String classname) throws ClassNotFoundException { if (classes.containsKey(classname)) return classes.get(classname);