[NOTHING CHANGED] Assorted fixes #48

Closed
asiekierka wants to merge 61 commits from asiekierka/master into master
106 changed files with 2457 additions and 1412 deletions
Showing only changes of commit bf23883492 - Show all commits

138
.ide/cleanup.xml Normal file
View File

@@ -0,0 +1,138 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<profiles version="2">
<profile kind="CleanUpProfile" name="Default" version="2">
<setting id="cleanup.array_with_curly" value="true"/>
<setting id="cleanup.use_autoboxing" value="true"/>
<setting id="cleanup.always_use_this_for_non_static_method_access" value="false"/>
<setting id="cleanup.remove_trailing_whitespaces_ignore_empty" value="false"/>
<setting id="cleanup.primitive_comparison" value="false"/>
<setting id="cleanup.system_property_file_encoding" value="true"/>
<setting id="cleanup.format_source_code_changes_only" value="false"/>
<setting id="cleanup.remove_redundant_semicolons" value="true"/>
<setting id="cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class" value="true"/>
<setting id="cleanup.useless_continue" value="true"/>
<setting id="cleanup.remove_redundant_type_arguments" value="true"/>
<setting id="cleanup.remove_unused_imports" value="true"/>
<setting id="cleanup.break_loop" value="false"/>
<setting id="cleanup.pull_up_assignment" value="false"/>
<setting id="cleanup.stringbuilder" value="false"/>
<setting id="cleanup.no_super" value="true"/>
<setting id="cleanup.arrays_fill" value="false"/>
<setting id="cleanup.use_lambda" value="true"/>
<setting id="cleanup.operand_factorization" value="false"/>
<setting id="cleanup.simplify_lambda_expression_and_method_ref" value="true"/>
<setting id="cleanup.always_use_blocks" value="true"/>
<setting id="cleanup.sort_members_all" value="false"/>
<setting id="cleanup.system_property_path_separator" value="true"/>
<setting id="cleanup.instanceof" value="false"/>
<setting id="cleanup.add_missing_annotations" value="true"/>
<setting id="cleanup.precompile_regex" value="false"/>
<setting id="cleanup.always_use_this_for_non_static_field_access" value="false"/>
<setting id="cleanup.boolean_literal" value="true"/>
<setting id="cleanup.always_use_parentheses_in_expressions" value="false"/>
<setting id="cleanup.sort_members" value="false"/>
<setting id="cleanup.remove_unused_local_variables" value="false"/>
<setting id="cleanup.add_missing_deprecated_annotations" value="true"/>
<setting id="cleanup.no_string_creation" value="true"/>
<setting id="cleanup.use_unboxing" value="false"/>
<setting id="cleanup.use_blocks_only_for_return_and_throw" value="false"/>
<setting id="cleanup.standard_comparison" value="false"/>
<setting id="cleanup.if_condition" value="true"/>
<setting id="cleanup.system_property_line_separator" value="true"/>
<setting id="cleanup.remove_trailing_whitespaces" value="true"/>
<setting id="cleanup.map_cloning" value="true"/>
<setting id="cleanup.add_serial_version_id" value="false"/>
<setting id="cleanup.try_with_resource" value="true"/>
<setting id="cleanup.use_this_for_non_static_method_access" value="false"/>
<setting id="cleanup.use_this_for_non_static_method_access_only_if_necessary" value="true"/>
<setting id="cleanup.single_used_field" value="false"/>
<setting id="cleanup.reduce_indentation" value="false"/>
<setting id="cleanup.primitive_parsing" value="false"/>
<setting id="cleanup.make_local_variable_final" value="false"/>
<setting id="cleanup.add_missing_methods" value="false"/>
<setting id="cleanup.qualify_static_member_accesses_with_declaring_class" value="true"/>
<setting id="cleanup.add_missing_override_annotations" value="true"/>
<setting id="cleanup.use_blocks" value="false"/>
<setting id="cleanup.multi_catch" value="true"/>
<setting id="cleanup.pull_out_if_from_if_else" value="true"/>
<setting id="cleanup.collection_cloning" value="true"/>
<setting id="cleanup.convert_to_enhanced_for_loop_if_loop_var_used" value="true"/>
<setting id="cleanup.make_variable_declarations_final" value="true"/>
<setting id="cleanup.redundant_comparator" value="false"/>
<setting id="cleanup.remove_unused_private_types" value="true"/>
<setting id="cleanup.system_property_boolean" value="true"/>
<setting id="cleanup.qualify_static_method_accesses_with_declaring_class" value="false"/>
<setting id="cleanup.organize_imports" value="true"/>
<setting id="cleanup.lazy_logical_operator" value="true"/>
<setting id="cleanup.bitwise_conditional_expression" value="false"/>
<setting id="cleanup.use_directly_map_method" value="false"/>
<setting id="cleanup.add_all" value="false"/>
<setting id="cleanup.system_property_file_separator" value="true"/>
<setting id="cleanup.qualify_static_field_accesses_with_declaring_class" value="false"/>
<setting id="cleanup.add_generated_serial_version_id" value="false"/>
<setting id="cleanup.controlflow_merge" value="false"/>
<setting id="cleanup.primitive_serialization" value="false"/>
<setting id="cleanup.comparing_on_criteria" value="true"/>
<setting id="cleanup.comparison_statement" value="true"/>
<setting id="cleanup.extract_increment" value="false"/>
<setting id="cleanup.insert_inferred_type_arguments" value="false"/>
<setting id="cleanup.make_private_fields_final" value="true"/>
<setting id="cleanup.useless_return" value="true"/>
<setting id="cleanup.instanceof_keyword" value="true"/>
<setting id="cleanup.use_this_for_non_static_field_access_only_if_necessary" value="true"/>
<setting id="cleanup.remove_trailing_whitespaces_all" value="true"/>
<setting id="cleanup.one_if_rather_than_duplicate_blocks_that_fall_through" value="true"/>
<setting id="cleanup.valueof_rather_than_instantiation" value="true"/>
<setting id="cleanup.plain_replacement" value="false"/>
<setting id="cleanup.remove_unnecessary_array_creation" value="true"/>
<setting id="cleanup.remove_private_constructors" value="true"/>
<setting id="cleanup.make_parameters_final" value="false"/>
<setting id="cleanup.substring" value="false"/>
<setting id="cleanup.ternary_operator" value="false"/>
<setting id="cleanup.merge_conditional_blocks" value="false"/>
<setting id="cleanup.return_expression" value="true"/>
<setting id="cleanup.system_property" value="true"/>
<setting id="cleanup.unlooped_while" value="true"/>
<setting id="cleanup.convert_to_enhanced_for_loop" value="true"/>
<setting id="cleanup.remove_unused_private_fields" value="true"/>
<setting id="cleanup.never_use_blocks" value="false"/>
<setting id="cleanup.remove_redundant_modifiers" value="true"/>
<setting id="cleanup.unreachable_block" value="false"/>
<setting id="cleanup.redundant_falling_through_block_end" value="false"/>
<setting id="cleanup.switch" value="false"/>
<setting id="cleanup.number_suffix" value="true"/>
<setting id="cleanup.remove_unnecessary_nls_tags" value="true"/>
<setting id="cleanup.convert_to_switch_expressions" value="false"/>
<setting id="cleanup.use_this_for_non_static_field_access" value="false"/>
<setting id="cleanup.static_inner_class" value="false"/>
<setting id="cleanup.use_string_is_blank" value="true"/>
<setting id="cleanup.add_missing_nls_tags" value="false"/>
<setting id="cleanup.qualify_static_member_accesses_through_instances_with_declaring_class" value="true"/>
<setting id="cleanup.remove_unnecessary_casts" value="true"/>
<setting id="cleanup.objects_equals" value="false"/>
<setting id="cleanup.convert_functional_interfaces" value="true"/>
<setting id="cleanup.format_source_code" value="true"/>
<setting id="cleanup.else_if" value="false"/>
<setting id="cleanup.boolean_value_rather_than_comparison" value="true"/>
<setting id="cleanup.add_default_serial_version_id" value="true"/>
<setting id="cleanup.remove_unused_private_methods" value="true"/>
<setting id="cleanup.make_type_abstract_if_missing_method" value="false"/>
<setting id="cleanup.join" value="false"/>
<setting id="cleanup.embedded_if" value="false"/>
<setting id="cleanup.use_anonymous_class_creation" value="false"/>
<setting id="cleanup.invert_equals" value="false"/>
<setting id="cleanup.add_missing_override_annotations_interface_methods" value="true"/>
<setting id="cleanup.remove_unused_private_members" value="false"/>
<setting id="cleanup.strictly_equal_or_different" value="true"/>
<setting id="cleanup.never_use_parentheses_in_expressions" value="true"/>
<setting id="cleanup.push_down_negation" value="false"/>
<setting id="cleanup.evaluate_nullable" value="false"/>
<setting id="cleanup.use_parentheses_in_expressions" value="true"/>
<setting id="cleanup.hash" value="false"/>
<setting id="cleanup.double_negation" value="true"/>
<setting id="cleanup.overridden_assignment" value="true"/>
<setting id="cleanup.primitive_rather_than_wrapper" value="true"/>
<setting id="cleanup.correct_indentation" value="false"/>
<setting id="cleanup.use_var" value="false"/>
</profile>
</profiles>

View File

@@ -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;
* <p>
* 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}
* <p>
* 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);

View File

@@ -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.
* <p>
*
*
* <h3>Constructing and Initializing Instances</h3> 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.
*
*
* <pre>
* {
* &#64;code
@@ -50,12 +50,12 @@ import org.luaj.vm2.lib.ResourceFinder;
* globals.load(new StringReader("print 'hello'"), "main.lua").call();
* }
* </pre>
*
*
* The creates a complete global environment with the standard libraries loaded.
* <p>
* For specialized circumstances, the Globals may be constructed directly and
* loaded with only those libraries that are needed, for example.
*
*
* <pre>
* {
* &#64;code
@@ -63,17 +63,17 @@ import org.luaj.vm2.lib.ResourceFinder;
* globals.load(new BaseLib());
* }
* </pre>
*
*
* <h3>Loading and Executing Lua Code</h3> Globals contains convenience
* functions to load and execute lua source code given a Reader. A simple
* example is:
*
*
* <pre>
* {@code
* globals.load( new StringReader("print 'hello'"), "main.lua" ).call();
* globals.load( new StringReader("print 'hello'"), "main.lua" ).call();
* }
* </pre>
*
*
* <h3>Fine-Grained Control of Compiling and Loading Lua</h3> Executable
* LuaFunctions are created from lua code in several steps
* <ul>
@@ -92,7 +92,7 @@ import org.luaj.vm2.lib.ResourceFinder;
* <li>convert lua bytecode to equivalent Java bytecode using
* {@link org.luaj.vm2.luajc.LuaJC} that implements {@link Loader} directly
* </ul>
*
*
* <h3>Java Field</h3> Certain public fields are provided that contain the
* current values of important global state:
* <ul>
@@ -107,7 +107,7 @@ import org.luaj.vm2.lib.ResourceFinder;
* <li>{@link #undumper} Current loaded {@link Undumper}, if any.
* <li>{@link #loader} Current loaded {@link Loader}, if any.
* </ul>
*
*
* <h3>Lua Environment Variables</h3> 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;
* <li>"_G" Pointer to this Globals.
* <li>"_VERSION" String containing the version of luaj.
* </ul>
*
*
* <h3>Use in Multithreaded Environments</h3> 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.
* <p>
*
*
* @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;
}

View File

@@ -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;
* <p>
* The canonical method to load and execute code is done indirectly using the
* Globals:
*
*
* <pre>
* {
* &#64;code
@@ -44,7 +44,7 @@ import java.io.InputStream;
* chunk.call();
* }
* </pre>
*
*
* This should work regardless of which {@link Globals.Compiler} or
* {@link Globals.Undumper} have been installed.
* <p>
@@ -53,10 +53,10 @@ import java.io.InputStream;
* {@link LoadState} default undumper is installed as the default
* {@link Globals.Undumper}.
* <p>
*
*
* A lua binary file is created via the {@link org.luaj.vm2.compiler.DumpState}
* class :
*
*
* <pre>
* {
* &#64;code
@@ -67,10 +67,10 @@ import java.io.InputStream;
* byte[] lua_binary_file_bytes = o.toByteArray();
* }
* </pre>
*
*
* The {@link LoadState}'s default undumper {@link #instance} may be used
* directly to undump these bytes:
*
*
* <pre>
* {@code
* Prototypep = LoadState.instance.undump(new ByteArrayInputStream(lua_binary_file_bytes), "main.lua");
@@ -78,10 +78,10 @@ import java.io.InputStream;
* c.call();
* }
* </pre>
*
*
*
*
* More commonly, the {@link Globals.Undumper} may be used to undump them:
*
*
* <pre>
* {
* &#64;code
@@ -90,7 +90,7 @@ import java.io.InputStream;
* c.call();
* }
* </pre>
*
*
* @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;
if ((f & intPrecMask) == 0) {
int intValue = (int) (f>>shift) | (1<<e);
return LuaInteger.valueOf(((bits>>63) != 0)? -intValue: intValue);
int intValue = (int) (f>>shift) | 1<<e;
return LuaInteger.valueOf(bits>>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);
}

View File

@@ -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

View File

@@ -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<<SIZE_OP)-1);
public static final int MAXARG_A = ((1<<SIZE_A)-1);
public static final int MAXARG_B = ((1<<SIZE_B)-1);
public static final int MAXARG_C = ((1<<SIZE_C)-1);
public static final int MAXARG_Bx = ((1<<SIZE_Bx)-1);
public static final int MAXARG_sBx = (MAXARG_Bx>>1); /* `sBx' is signed */
public static final int MAXARG_Ax = ((1<<SIZE_Ax)-1);
public static final int MAX_OP = (1<<SIZE_OP)-1;
public static final int MAXARG_A = (1<<SIZE_A)-1;
public static final int MAXARG_B = (1<<SIZE_B)-1;
public static final int MAXARG_C = (1<<SIZE_C)-1;
public static final int MAXARG_Bx = (1<<SIZE_Bx)-1;
public static final int MAXARG_sBx = MAXARG_Bx>>1; /* `sBx' is signed */
public static final int MAXARG_Ax = (1<<SIZE_Ax)-1;
public static final int MASK_OP = ((1<<SIZE_OP)-1)<<POS_OP;
public static final int MASK_A = ((1<<SIZE_A)-1)<<POS_A;
public static final int MASK_B = ((1<<SIZE_B)-1)<<POS_B;
public static final int MASK_C = ((1<<SIZE_C)-1)<<POS_C;
public static final int MASK_Bx = ((1<<SIZE_Bx)-1)<<POS_Bx;
public static final int MASK_Ax = ((1<<SIZE_Ax)-1)<<POS_Ax;
public static final int MASK_OP = (1<<SIZE_OP)-1<<POS_OP;
public static final int MASK_A = (1<<SIZE_A)-1<<POS_A;
public static final int MASK_B = (1<<SIZE_B)-1<<POS_B;
public static final int MASK_C = (1<<SIZE_C)-1<<POS_C;
public static final int MASK_Bx = (1<<SIZE_Bx)-1<<POS_Bx;
public static final int MASK_Ax = (1<<SIZE_Ax)-1<<POS_Ax;
public static final int MASK_NOT_OP = ~MASK_OP;
public static final int MASK_NOT_A = ~MASK_A;
@@ -102,31 +102,31 @@ public class Lua {
** the following macros help to manipulate instructions
*/
public static int GET_OPCODE(int i) {
return (i>>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<<SIZE_B-1;
/** test whether value is a constant */
public static boolean ISK(int x) {
return 0 != ((x) & BITRK);
return 0 != (x & BITRK);
}
/** gets the index of the constant */
public static int INDEXK(int r) {
return ((int) (r) & ~BITRK);
return r & ~BITRK;
}
public static final int MAXINDEXRK = (BITRK-1);
public static final int MAXINDEXRK = BITRK-1;
/** code a constant index as a RK value */
public static int RKASK(int x) {
return ((x) | BITRK);
return x | BITRK;
}
/**
@@ -272,46 +272,46 @@ public class Lua {
public static final int[] luaP_opmodes = {
/* T A B C mode opcode */
(0<<7) | (1<<6) | (OpArgR<<4) | (OpArgN<<2) | (iABC), /* OP_MOVE */
(0<<7) | (1<<6) | (OpArgK<<4) | (OpArgN<<2) | (iABx), /* OP_LOADK */
(0<<7) | (1<<6) | (OpArgN<<4) | (OpArgN<<2) | (iABx), /* OP_LOADKX */
(0<<7) | (1<<6) | (OpArgU<<4) | (OpArgU<<2) | (iABC), /* OP_LOADBOOL */
(0<<7) | (1<<6) | (OpArgU<<4) | (OpArgN<<2) | (iABC), /* OP_LOADNIL */
(0<<7) | (1<<6) | (OpArgU<<4) | (OpArgN<<2) | (iABC), /* OP_GETUPVAL */
(0<<7) | (1<<6) | (OpArgU<<4) | (OpArgK<<2) | (iABC), /* OP_GETTABUP */
(0<<7) | (1<<6) | (OpArgR<<4) | (OpArgK<<2) | (iABC), /* OP_GETTABLE */
(0<<7) | (0<<6) | (OpArgK<<4) | (OpArgK<<2) | (iABC), /* OP_SETTABUP */
(0<<7) | (0<<6) | (OpArgU<<4) | (OpArgN<<2) | (iABC), /* OP_SETUPVAL */
(0<<7) | (0<<6) | (OpArgK<<4) | (OpArgK<<2) | (iABC), /* OP_SETTABLE */
(0<<7) | (1<<6) | (OpArgU<<4) | (OpArgU<<2) | (iABC), /* OP_NEWTABLE */
(0<<7) | (1<<6) | (OpArgR<<4) | (OpArgK<<2) | (iABC), /* OP_SELF */
(0<<7) | (1<<6) | (OpArgK<<4) | (OpArgK<<2) | (iABC), /* OP_ADD */
(0<<7) | (1<<6) | (OpArgK<<4) | (OpArgK<<2) | (iABC), /* OP_SUB */
(0<<7) | (1<<6) | (OpArgK<<4) | (OpArgK<<2) | (iABC), /* OP_MUL */
(0<<7) | (1<<6) | (OpArgK<<4) | (OpArgK<<2) | (iABC), /* OP_DIV */
(0<<7) | (1<<6) | (OpArgK<<4) | (OpArgK<<2) | (iABC), /* OP_MOD */
(0<<7) | (1<<6) | (OpArgK<<4) | (OpArgK<<2) | (iABC), /* OP_POW */
(0<<7) | (1<<6) | (OpArgR<<4) | (OpArgN<<2) | (iABC), /* OP_UNM */
(0<<7) | (1<<6) | (OpArgR<<4) | (OpArgN<<2) | (iABC), /* OP_NOT */
(0<<7) | (1<<6) | (OpArgR<<4) | (OpArgN<<2) | (iABC), /* OP_LEN */
(0<<7) | (1<<6) | (OpArgR<<4) | (OpArgR<<2) | (iABC), /* OP_CONCAT */
(0<<7) | (0<<6) | (OpArgR<<4) | (OpArgN<<2) | (iAsBx), /* OP_JMP */
(1<<7) | (0<<6) | (OpArgK<<4) | (OpArgK<<2) | (iABC), /* OP_EQ */
(1<<7) | (0<<6) | (OpArgK<<4) | (OpArgK<<2) | (iABC), /* OP_LT */
(1<<7) | (0<<6) | (OpArgK<<4) | (OpArgK<<2) | (iABC), /* OP_LE */
(1<<7) | (0<<6) | (OpArgN<<4) | (OpArgU<<2) | (iABC), /* OP_TEST */
(1<<7) | (1<<6) | (OpArgR<<4) | (OpArgU<<2) | (iABC), /* OP_TESTSET */
(0<<7) | (1<<6) | (OpArgU<<4) | (OpArgU<<2) | (iABC), /* OP_CALL */
(0<<7) | (1<<6) | (OpArgU<<4) | (OpArgU<<2) | (iABC), /* OP_TAILCALL */
(0<<7) | (0<<6) | (OpArgU<<4) | (OpArgN<<2) | (iABC), /* OP_RETURN */
(0<<7) | (1<<6) | (OpArgR<<4) | (OpArgN<<2) | (iAsBx), /* OP_FORLOOP */
(0<<7) | (1<<6) | (OpArgR<<4) | (OpArgN<<2) | (iAsBx), /* OP_FORPREP */
(0<<7) | (0<<6) | (OpArgN<<4) | (OpArgU<<2) | (iABC), /* OP_TFORCALL */
(1<<7) | (1<<6) | (OpArgR<<4) | (OpArgN<<2) | (iAsBx), /* OP_TFORLOOP */
(0<<7) | (0<<6) | (OpArgU<<4) | (OpArgU<<2) | (iABC), /* OP_SETLIST */
(0<<7) | (1<<6) | (OpArgU<<4) | (OpArgN<<2) | (iABx), /* OP_CLOSURE */
(0<<7) | (1<<6) | (OpArgU<<4) | (OpArgN<<2) | (iABC), /* OP_VARARG */
(0<<7) | (0<<6) | (OpArgU<<4) | (OpArgU<<2) | (iAx), /* OP_EXTRAARG */
0<<7 | 1<<6 | OpArgR<<4 | OpArgN<<2 | iABC, /* OP_MOVE */
0<<7 | 1<<6 | OpArgK<<4 | OpArgN<<2 | iABx, /* OP_LOADK */
0<<7 | 1<<6 | OpArgN<<4 | OpArgN<<2 | iABx, /* OP_LOADKX */
0<<7 | 1<<6 | OpArgU<<4 | OpArgU<<2 | iABC, /* OP_LOADBOOL */
0<<7 | 1<<6 | OpArgU<<4 | OpArgN<<2 | iABC, /* OP_LOADNIL */
0<<7 | 1<<6 | OpArgU<<4 | OpArgN<<2 | iABC, /* OP_GETUPVAL */
0<<7 | 1<<6 | OpArgU<<4 | OpArgK<<2 | iABC, /* OP_GETTABUP */
0<<7 | 1<<6 | OpArgR<<4 | OpArgK<<2 | iABC, /* OP_GETTABLE */
0<<7 | 0<<6 | OpArgK<<4 | OpArgK<<2 | iABC, /* OP_SETTABUP */
0<<7 | 0<<6 | OpArgU<<4 | OpArgN<<2 | iABC, /* OP_SETUPVAL */
0<<7 | 0<<6 | OpArgK<<4 | OpArgK<<2 | iABC, /* OP_SETTABLE */
0<<7 | 1<<6 | OpArgU<<4 | OpArgU<<2 | iABC, /* OP_NEWTABLE */
0<<7 | 1<<6 | OpArgR<<4 | OpArgK<<2 | iABC, /* OP_SELF */
0<<7 | 1<<6 | OpArgK<<4 | OpArgK<<2 | iABC, /* OP_ADD */
0<<7 | 1<<6 | OpArgK<<4 | OpArgK<<2 | iABC, /* OP_SUB */
0<<7 | 1<<6 | OpArgK<<4 | OpArgK<<2 | iABC, /* OP_MUL */
0<<7 | 1<<6 | OpArgK<<4 | OpArgK<<2 | iABC, /* OP_DIV */
0<<7 | 1<<6 | OpArgK<<4 | OpArgK<<2 | iABC, /* OP_MOD */
0<<7 | 1<<6 | OpArgK<<4 | OpArgK<<2 | iABC, /* OP_POW */
0<<7 | 1<<6 | OpArgR<<4 | OpArgN<<2 | iABC, /* OP_UNM */
0<<7 | 1<<6 | OpArgR<<4 | OpArgN<<2 | iABC, /* OP_NOT */
0<<7 | 1<<6 | OpArgR<<4 | OpArgN<<2 | iABC, /* OP_LEN */
0<<7 | 1<<6 | OpArgR<<4 | OpArgR<<2 | iABC, /* OP_CONCAT */
0<<7 | 0<<6 | OpArgR<<4 | OpArgN<<2 | iAsBx, /* OP_JMP */
1<<7 | 0<<6 | OpArgK<<4 | OpArgK<<2 | iABC, /* OP_EQ */
1<<7 | 0<<6 | OpArgK<<4 | OpArgK<<2 | iABC, /* OP_LT */
1<<7 | 0<<6 | OpArgK<<4 | OpArgK<<2 | iABC, /* OP_LE */
1<<7 | 0<<6 | OpArgN<<4 | OpArgU<<2 | iABC, /* OP_TEST */
1<<7 | 1<<6 | OpArgR<<4 | OpArgU<<2 | iABC, /* OP_TESTSET */
0<<7 | 1<<6 | OpArgU<<4 | OpArgU<<2 | iABC, /* OP_CALL */
0<<7 | 1<<6 | OpArgU<<4 | OpArgU<<2 | iABC, /* OP_TAILCALL */
0<<7 | 0<<6 | OpArgU<<4 | OpArgN<<2 | iABC, /* OP_RETURN */
0<<7 | 1<<6 | OpArgR<<4 | OpArgN<<2 | iAsBx, /* OP_FORLOOP */
0<<7 | 1<<6 | OpArgR<<4 | OpArgN<<2 | iAsBx, /* OP_FORPREP */
0<<7 | 0<<6 | OpArgN<<4 | OpArgU<<2 | iABC, /* OP_TFORCALL */
1<<7 | 1<<6 | OpArgR<<4 | OpArgN<<2 | iAsBx, /* OP_TFORLOOP */
0<<7 | 0<<6 | OpArgU<<4 | OpArgU<<2 | iABC, /* OP_SETLIST */
0<<7 | 1<<6 | OpArgU<<4 | OpArgN<<2 | iABx, /* OP_CLOSURE */
0<<7 | 1<<6 | OpArgU<<4 | OpArgN<<2 | iABC, /* OP_VARARG */
0<<7 | 0<<6 | OpArgU<<4 | OpArgU<<2 | iAx, /* OP_EXTRAARG */
};
public static int getOpMode(int m) {
@@ -319,19 +319,19 @@ public class Lua {
}
public static int getBMode(int m) {
return (luaP_opmodes[m]>>4) & 3;
return luaP_opmodes[m]>>4 & 3;
}
public static int getCMode(int m) {
return (luaP_opmodes[m]>>2) & 3;
return luaP_opmodes[m]>>2 & 3;
}
public static boolean testAMode(int m) {
return 0 != (luaP_opmodes[m] & (1<<6));
return 0 != (luaP_opmodes[m] & 1<<6);
}
public static boolean testTMode(int m) {
return 0 != (luaP_opmodes[m] & (1<<7));
return 0 != (luaP_opmodes[m] & 1<<7);
}
/* number of list items to accumulate before a SETLIST instruction */

View File

@@ -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()}
* <p>
*
*
* @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;
}

View File

@@ -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.
*
*
* <p>
* There are three main ways {@link LuaClosure} instances are created:
* <ul>
@@ -43,7 +43,7 @@ import org.luaj.vm2.lib.DebugLib.CallFrame;
* <p>
* To construct it directly, the {@link Prototype} is typically created via a
* compiler such as {@link org.luaj.vm2.compiler.LuaC}:
*
*
* <pre>
* {
* &#64;code
@@ -58,7 +58,7 @@ import org.luaj.vm2.lib.DebugLib.CallFrame;
* <p>
* To construct it indirectly, the {@link Globals#load(java.io.Reader, String)}
* method may be used:
*
*
* <pre>
* {
* &#64;code
@@ -87,7 +87,7 @@ import org.luaj.vm2.lib.DebugLib.CallFrame;
* <li>{@link LuaValue#invokemethod(String,Varargs)}</li>
* <li>...</li>
* </ul>
*
*
* @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<<Lua.POS_B) | (0<<Lua.POS_C):
case 1<<Lua.POS_B | 0<<Lua.POS_C:
v = stack[a].invoke(NONE);
top = a+v.narg();
continue;
case (2<<Lua.POS_B) | (0<<Lua.POS_C):
case 2<<Lua.POS_B | 0<<Lua.POS_C:
v = stack[a].invoke(stack[a+1]);
top = a+v.narg();
continue;
case (1<<Lua.POS_B) | (1<<Lua.POS_C):
case 1<<Lua.POS_B | 1<<Lua.POS_C:
stack[a].call();
continue;
case (2<<Lua.POS_B) | (1<<Lua.POS_C):
case 2<<Lua.POS_B | 1<<Lua.POS_C:
stack[a].call(stack[a+1]);
continue;
case (3<<Lua.POS_B) | (1<<Lua.POS_C):
case 3<<Lua.POS_B | 1<<Lua.POS_C:
stack[a].call(stack[a+1], stack[a+2]);
continue;
case (4<<Lua.POS_B) | (1<<Lua.POS_C):
case 4<<Lua.POS_B | 1<<Lua.POS_C:
stack[a].call(stack[a+1], stack[a+2], stack[a+3]);
continue;
case (1<<Lua.POS_B) | (2<<Lua.POS_C):
case 1<<Lua.POS_B | 2<<Lua.POS_C:
stack[a] = stack[a].call();
continue;
case (2<<Lua.POS_B) | (2<<Lua.POS_C):
case 2<<Lua.POS_B | 2<<Lua.POS_C:
stack[a] = stack[a].call(stack[a+1]);
continue;
case (3<<Lua.POS_B) | (2<<Lua.POS_C):
case 3<<Lua.POS_B | 2<<Lua.POS_C:
stack[a] = stack[a].call(stack[a+1], stack[a+2]);
continue;
case (4<<Lua.POS_B) | (2<<Lua.POS_C):
case 4<<Lua.POS_B | 2<<Lua.POS_C:
stack[a] = stack[a].call(stack[a+1], stack[a+2], stack[a+3]);
continue;
default:
b = i>>>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<<Lua.POS_B):
case 1<<Lua.POS_B:
return new TailcallVarargs(stack[a], NONE);
case (2<<Lua.POS_B):
case 2<<Lua.POS_B:
return new TailcallVarargs(stack[a], stack[a+1]);
case (3<<Lua.POS_B):
case 3<<Lua.POS_B:
return new TailcallVarargs(stack[a], varargsOf(stack[a+1], stack[a+2]));
case (4<<Lua.POS_B):
case 4<<Lua.POS_B:
return new TailcallVarargs(stack[a], varargsOf(stack[a+1], stack[a+2], stack[a+3]));
default:
b = i>>>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 + ">";
}

View File

@@ -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;
* <li>{@link #dmod_d(double, double)}</li>
* </ul>
* <p>
*
*
* @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);
}

View File

@@ -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.
* <p>
* 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; }
}

View File

@@ -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() {

View File

@@ -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;
* <p>
* 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));
}

View File

@@ -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; }
}

View File

@@ -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;
* <p>
* 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); }
}

View File

@@ -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.
* <p>
*
*
* @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.
* <p>
*
*
* @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 {
* <p>
* 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 {
* <p>
* 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.
* <p>
*
*
* @param bytes byte buffer
* @return {@link LuaString} wrapping the byte buffer
*/
@@ -252,7 +252,7 @@ public class LuaString extends LuaValue {
* <p>
* 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.
* <p>
*
*
* @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 {
* <p>
* 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) {

View File

@@ -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;
* </ul>
* <p>
* To iterate over key-value pairs from Java, use
*
*
* <pre>
* {@code
* LuaValue k = LuaValue.NIL;
@@ -57,7 +57,7 @@ import java.util.Vector;
* process( k, v )
* }}
* </pre>
*
*
* <p>
* 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;
* <li>{@link LuaValue#tableOf(LuaValue[], LuaValue[], Varargs)} initialize
* array and named parts</li>
* </ul>
*
*
* @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<<log2(narray));
@@ -185,8 +191,8 @@ public class LuaTable extends LuaValue implements Metatable {
if (nhash > 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<<log2(narray)]: NOVALS);
hash = (nhash > 0? new Slot[1<<log2(nhash)]: NOBUCKETS);
array = narray > 0? new LuaValue[1<<log2(narray)]: NOVALS;
hash = nhash > 0? new Slot[1<<log2(nhash)]: NOBUCKETS;
hashEntries = 0;
}
@@ -199,7 +205,7 @@ public class LuaTable extends LuaValue implements Metatable {
/**
* Get the length of the array part of the table.
*
*
* @return length of the array part, does not relate to count of objects in
* the table.
*/
@@ -207,38 +213,43 @@ public class LuaTable extends LuaValue implements Metatable {
/**
* Get the length of the hash part of the table.
*
*
* @return length of the hash part, does not relate to count of objects in
* the table.
*/
protected int getHashLength() { return hash.length; }
@Override
public LuaValue getmetatable() {
return (m_metatable != null)? m_metatable.toLuaValue(): null;
return m_metatable != null? m_metatable.toLuaValue(): null;
}
@Override
public LuaValue setmetatable(LuaValue metatable) {
boolean hadWeakKeys = m_metatable != null && m_metatable.useWeakKeys();
boolean hadWeakValues = m_metatable != null && m_metatable.useWeakValues();
m_metatable = metatableOf(metatable);
if ((hadWeakKeys != (m_metatable != null && m_metatable.useWeakKeys()))
|| (hadWeakValues != (m_metatable != null && m_metatable.useWeakValues()))) {
if (hadWeakKeys != (m_metatable != null && m_metatable.useWeakKeys())
|| hadWeakValues != (m_metatable != null && m_metatable.useWeakValues())) {
// force a rehash
rehash(0);
}
return this;
}
@Override
public LuaValue get(int key) {
LuaValue v = rawget(key);
return v.isnil() && m_metatable != null? gettable(this, valueOf(key)): v;
}
@Override
public LuaValue get(LuaValue key) {
LuaValue v = rawget(key);
return v.isnil() && m_metatable != null? gettable(this, key): v;
}
@Override
public LuaValue rawget(int key) {
if (key > 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<<log) {
// Not enough integer keys.
break;
} else if (keys >= (1<<(log-1))) {
} else if (keys >= 1<<log-1) {
newArraySize = 1<<log;
}
}
@@ -741,14 +762,14 @@ public class LuaTable extends LuaValue implements Metatable {
newArray = array;
}
final int newHashSize = hashEntries-movingToArray+((newKey < 0 || newKey > 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<<log2(newHashSize);
newCapacity = newHashSize < MIN_HASH_CAPACITY? MIN_HASH_CAPACITY: 1<<log2(newHashSize);
newHashMask = newCapacity-1;
newHash = new Slot[newCapacity];
} else {
@@ -785,7 +806,7 @@ public class LuaTable extends LuaValue implements Metatable {
} else {
newEntry = defaultEntry(valueOf(i), v);
}
newHash[slot] = (newHash[slot] != null)? newHash[slot].add(newEntry): newEntry;
newHash[slot] = newHash[slot] != null? newHash[slot].add(newEntry): newEntry;
}
}
@@ -794,6 +815,7 @@ public class LuaTable extends LuaValue implements Metatable {
hashEntries -= movingToArray;
}
@Override
public Slot entry(LuaValue key, LuaValue value) {
return defaultEntry(key, value);
}
@@ -828,11 +850,11 @@ public class LuaTable extends LuaValue implements Metatable {
//
/**
* Sort the table using a comparator.
*
*
* @param comparator {@link LuaValue} to be called to compare elements.
*/
public void sort(LuaValue comparator) {
if (len().tolong() >= (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.
*
*
* <p>
* 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("<dead");
@@ -1412,28 +1495,33 @@ public class LuaTable extends LuaValue implements Metatable {
}
return buf.toString();
}
};
}
private static final Slot[] NOBUCKETS = {};
// Metatable operations
@Override
public boolean useWeakKeys() {
return false;
}
@Override
public boolean useWeakValues() {
return false;
}
@Override
public LuaValue toLuaValue() {
return this;
}
@Override
public LuaValue wrap(LuaValue value) {
return value;
}
@Override
public LuaValue arrayget(LuaValue[] array, int index) {
return array[index];
}

View File

@@ -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 java.lang.ref.WeakReference;
* dead state. In either case all references to the thread must be dropped, and
* the garbage collector must run for the thread to be garbage collected.
*
*
*
* @see LuaValue
* @see org.luaj.vm2.lib.jse.JsePlatform
* @see org.luaj.vm2.lib.jme.JmePlatform
@@ -112,7 +112,7 @@ public class LuaThread extends LuaValue {
/**
* Create a LuaThread around a function and environment
*
*
* @param func The function to execute
*/
public LuaThread(Globals globals, LuaValue func) {
@@ -121,26 +121,32 @@ public class LuaThread extends LuaValue {
this.globals = globals;
}
@Override
public int type() {
return LuaValue.TTHREAD;
}
@Override
public String typename() {
return "thread";
}
@Override
public boolean isthread() {
return true;
}
@Override
public LuaThread optthread(LuaThread defval) {
return this;
}
@Override
public LuaThread checkthread() {
return this;
}
@Override
public LuaValue getmetatable() {
return s_metatable;
}
@@ -184,6 +190,7 @@ public class LuaThread extends LuaValue {
this.function = function;
}
@Override
public synchronized void run() {
try {
Varargs a = this.args;
@@ -212,8 +219,8 @@ public class LuaThread extends LuaValue {
previous_thread.state.status = STATUS_NORMAL;
this.status = STATUS_RUNNING;
this.wait();
return (this.error != null? LuaValue.varargsOf(LuaValue.FALSE, LuaValue.valueOf(this.error))
: LuaValue.varargsOf(LuaValue.TRUE, this.result));
return this.error != null? LuaValue.varargsOf(LuaValue.FALSE, LuaValue.valueOf(this.error))
: LuaValue.varargsOf(LuaValue.TRUE, this.result);
} catch (InterruptedException ie) {
throw new OrphanedThread();
} finally {

View File

@@ -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,18 +35,22 @@ public class LuaUserdata extends LuaValue {
m_metatable = metatable;
}
@Override
public String tojstring() {
return String.valueOf(m_instance);
}
@Override
public int type() {
return LuaValue.TUSERDATA;
}
@Override
public String typename() {
return "userdata";
}
@Override
public int hashCode() {
return m_instance.hashCode();
}
@@ -55,50 +59,63 @@ public class LuaUserdata extends LuaValue {
return m_instance;
}
@Override
public boolean isuserdata() { return true; }
@Override
public boolean isuserdata(Class c) { return c.isAssignableFrom(m_instance.getClass()); }
@Override
public Object touserdata() { return m_instance; }
@Override
public Object touserdata(Class c) { return c.isAssignableFrom(m_instance.getClass())? m_instance: null; }
@Override
public Object optuserdata(Object defval) { return m_instance; }
@Override
public Object optuserdata(Class c, Object defval) {
if (!c.isAssignableFrom(m_instance.getClass()))
typerror(c.getName());
return m_instance;
}
@Override
public LuaValue getmetatable() {
return m_metatable;
}
@Override
public LuaValue setmetatable(LuaValue metatable) {
this.m_metatable = metatable;
return this;
}
@Override
public Object checkuserdata() {
return m_instance;
}
@Override
public Object checkuserdata(Class c) {
if (c.isAssignableFrom(m_instance.getClass()))
return m_instance;
return typerror(c.getName());
}
@Override
public LuaValue get(LuaValue key) {
return m_metatable != null? gettable(this, key): NIL;
}
@Override
public void set(LuaValue key, LuaValue value) {
if (m_metatable == null || !settable(this, key, value))
error("cannot set " + key + " for userdata");
}
@Override
public boolean equals(Object val) {
if (this == val)
return true;
@@ -109,8 +126,10 @@ public class LuaUserdata extends LuaValue {
}
// equality w/ metatable processing
@Override
public LuaValue eq(LuaValue val) { return eq_b(val)? TRUE: FALSE; }
@Override
public boolean eq_b(LuaValue val) {
if (val.raweq(this))
return true;
@@ -121,10 +140,12 @@ public class LuaUserdata extends LuaValue {
}
// equality w/o metatable processing
@Override
public boolean raweq(LuaValue val) { return val.raweq(this); }
@Override
public boolean raweq(LuaUserdata val) {
return this == val || (m_metatable == val.m_metatable && m_instance.equals(val.m_instance));
return this == val || m_metatable == val.m_metatable && m_instance.equals(val.m_instance);
}
// __eq metatag processing

File diff suppressed because it is too large Load Diff

View File

@@ -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);
}

View File

@@ -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];
}

View File

@@ -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

View File

@@ -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}

View File

@@ -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.
*
*
* <p>
* This is both a straight translation of the corresponding C type, and the main
* data structure for execution of compiled lua bytecode.
*
*
* <p>
* 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)}:
*
*
* <pre>
* {
* &#64;code
@@ -40,11 +40,11 @@ package org.luaj.vm2;
* globals.load(new StringReader("print 'hello'"), "main.lua").call();
* }
* </pre>
*
*
* <p>
* To create a {@link Prototype} directly, a compiler such as
* {@link org.luaj.vm2.compiler.LuaC} may be used:
*
*
* <pre>
* {
* &#64;code
@@ -52,31 +52,31 @@ package org.luaj.vm2;
* Prototype p = LuaC.instance.compile(is, "script");
* }
* </pre>
*
*
* To simplify loading, the
* {@link Globals#compilePrototype(java.io.InputStream, String)} method may be
* used:
*
*
* <pre>
* {
* &#64;code
* Prototype p = globals.compileProtoytpe(is, "script");
* }
* </pre>
*
*
* It may also be loaded from a {@link java.io.Reader} via
* {@link Globals#compilePrototype(java.io.Reader, String)}:
*
*
* <pre>
* {
* &#64;code
* Prototype p = globals.compileProtoytpe(new StringReader(script), "script");
* }
* </pre>
*
*
* 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:
*
*
* <pre>
* {
* &#64;code
@@ -84,10 +84,10 @@ package org.luaj.vm2;
* Prototype p = globals.undumper.undump(lua_binary_file, "foo.lua");
* }
* </pre>
*
*
* To execute the code represented by the {@link Prototype} it must be supplied
* to the constructor of a {@link LuaClosure}:
*
*
* <pre>
* {
* &#64;code
@@ -96,17 +96,17 @@ package org.luaj.vm2;
* f.call();
* }
* </pre>
*
*
* To simplify the debugging of prototype values, the contents may be printed
* using {@link Print#print}:
*
*
* <pre>
* {@code
* Print.print(p);
* }
* </pre>
* <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

View File

@@ -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;
* <p>
* 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();

View File

@@ -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
* <p>
*
*
* @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;

View File

@@ -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);
}

View File

@@ -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)}
* <p>
*
*
* @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 {
* <p>
* 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 {
* <p>
* 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 {
* <p>
* 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 {
* <p>
* 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 {
* <p>
* 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 {
* <p>
* 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 {
* <p>
* 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

View File

@@ -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) {

View File

@@ -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<<POS_OP) & MASK_OP));
i.set(i.get() & MASK_NOT_OP | o<<POS_OP & MASK_OP);
}
static void SETARG_A(int[] code, int index, int u) {
code[index] = (code[index] & (MASK_NOT_A)) | ((u<<POS_A) & MASK_A);
code[index] = code[index] & MASK_NOT_A | u<<POS_A & MASK_A;
}
static void SETARG_A(InstructionPtr i, int u) {
i.set((i.get() & (MASK_NOT_A)) | ((u<<POS_A) & MASK_A));
i.set(i.get() & MASK_NOT_A | u<<POS_A & MASK_A);
}
static void SETARG_B(InstructionPtr i, int u) {
i.set((i.get() & (MASK_NOT_B)) | ((u<<POS_B) & MASK_B));
i.set(i.get() & MASK_NOT_B | u<<POS_B & MASK_B);
}
static void SETARG_C(InstructionPtr i, int u) {
i.set((i.get() & (MASK_NOT_C)) | ((u<<POS_C) & MASK_C));
i.set(i.get() & MASK_NOT_C | u<<POS_C & MASK_C);
}
static void SETARG_Bx(InstructionPtr i, int u) {
i.set((i.get() & (MASK_NOT_Bx)) | ((u<<POS_Bx) & MASK_Bx));
i.set(i.get() & MASK_NOT_Bx | u<<POS_Bx & MASK_Bx);
}
static void SETARG_sBx(InstructionPtr i, int u) {
@@ -87,15 +87,15 @@ public class Constants extends Lua {
}
static int CREATE_ABC(int o, int a, int b, int c) {
return ((o<<POS_OP) & MASK_OP) | ((a<<POS_A) & MASK_A) | ((b<<POS_B) & MASK_B) | ((c<<POS_C) & MASK_C);
return o<<POS_OP & MASK_OP | a<<POS_A & MASK_A | b<<POS_B & MASK_B | c<<POS_C & MASK_C;
}
static int CREATE_ABx(int o, int a, int bc) {
return ((o<<POS_OP) & MASK_OP) | ((a<<POS_A) & MASK_A) | ((bc<<POS_Bx) & MASK_Bx);
return o<<POS_OP & MASK_OP | a<<POS_A & MASK_A | bc<<POS_Bx & MASK_Bx;
}
static int CREATE_Ax(int o, int a) {
return ((o<<POS_OP) & MASK_OP) | ((a<<POS_Ax) & MASK_Ax);
return o<<POS_OP & MASK_OP | a<<POS_Ax & MASK_Ax;
}
// vector reallocation

View File

@@ -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.Prototype;
* command line interface tool such as {@link luac}.
* <p>
* A lua binary file is created via {@link DumpState#dump}:
*
*
* <pre>
* {
* &#64;code
@@ -51,9 +51,9 @@ import org.luaj.vm2.Prototype;
* byte[] lua_binary_file_bytes = o.toByteArray();
* }
* </pre>
*
*
* The {@link LoadState} may be used directly to undump these bytes:
*
*
* <pre>
* {@code
* Prototypep = LoadState.instance.undump(new ByteArrayInputStream(lua_binary_file_bytes), "main.lua");
@@ -61,10 +61,10 @@ import org.luaj.vm2.Prototype;
* c.call();
* }
* </pre>
*
*
*
*
* More commonly, the {@link Globals#undumper} may be used to undump them:
*
*
* <pre>
* {
* &#64;code
@@ -73,7 +73,7 @@ import org.luaj.vm2.Prototype;
* c.call();
* }
* </pre>
*
*
* @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;

View File

@@ -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);

View File

@@ -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

View File

@@ -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

View File

@@ -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("<name> 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);
}

View File

@@ -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.
*
*
* <p>
* 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.
*
*
* <p>
* 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.
*
*
* <p>
* 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:
*
*
* <pre>
* {
* &#64;code
@@ -60,15 +60,15 @@ import org.luaj.vm2.lib.BaseLib;
* globals.load(new StringReader("print 'hello'"), "main.lua").call();
* }
* </pre>
*
*
* To load the LuaC compiler manually, use the install method:
*
*
* <pre>
* {@code
* LuaC.install(globals);
* }
* </pre>
*
*
* @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;
}

View File

@@ -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()}
*
*
* <pre>
* {
* &#64;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:
*
*
* <pre>
* {
* &#64;code
@@ -71,12 +71,12 @@ import org.luaj.vm2.Varargs;
* globals.get("print").call(LuaValue.valueOf("hello, world"));
* }
* </pre>
*
*
* Doing so will ensure the library is properly initialized and loaded into the
* globals table.
* <p>
* 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;

View File

@@ -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()}
*
*
* <pre>
* {
* &#64;code
@@ -43,7 +43,7 @@ import org.luaj.vm2.Varargs;
* <p>
* To instantiate and use it directly, link it into your globals table via
* {@link LuaValue#load(LuaValue)} using code such as:
*
*
* <pre>
* {
* &#64;code
@@ -57,7 +57,7 @@ import org.luaj.vm2.Varargs;
* <p>
* 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<<disp) | (x>>>(32-disp)));
return bitsToValue(x<<disp | 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))<<field;
n = (n & ~mask) | ((v<<field) & mask);
int mask = -1>>>32-width<<field;
n = n & ~mask | v<<field & mask;
return bitsToValue(n);
}
private static LuaValue bitsToValue(int x) {
return (x < 0)? valueOf((double) ((long) x & 0xFFFFFFFFL)): valueOf(x);
return x < 0? valueOf(x & 0xFFFFFFFFL): valueOf(x);
}
}

View File

@@ -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;
* 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()}
*
*
* <pre>
* {
* &#64;code
@@ -52,7 +52,7 @@ import org.luaj.vm2.Varargs;
* <p>
* To instantiate and use it directly, link it into your globals table via
* {@link LuaValue#load(LuaValue)} using code such as:
*
*
* <pre>
* {
* &#64;code
@@ -64,7 +64,7 @@ import org.luaj.vm2.Varargs;
* }
* </pre>
* <p>
*
*
* @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()) {

View File

@@ -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()}
*
*
* <pre>
* {
* &#64;code
@@ -63,7 +63,7 @@ import org.luaj.vm2.Varargs;
* <p>
* To instantiate and use it directly, link it into your globals table via
* {@link LuaValue#load(LuaValue)} using code such as:
*
*
* <pre>
* {
* &#64;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;
}

View File

@@ -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()}
*
*
* <pre>
* {
* &#64;code
@@ -55,7 +55,7 @@ import org.luaj.vm2.Varargs;
* globals.get("io").get("write").call(LuaValue.valueOf("hello, world\n"));
* }
* </pre>
*
*
* 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;
* <p>
* To instantiate and use it directly, link it into your globals table via
* {@link LuaValue#load(LuaValue)} using code such as:
*
*
* <pre>
* {
* &#64;code
@@ -77,7 +77,7 @@ import org.luaj.vm2.Varargs;
* <p>
* 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 <a href=
* "http://www.lua.org/manual/5.1/manual.html#5.7">http://www.lua.org/manual/5.1/manual.html#5.7</a>
*/
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;

View File

@@ -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;
* <p>
* For example, the following code will implement a library called "hyperbolic"
* with two functions, "sinh", and "cosh":
*
*
* <pre>
* {@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;
*}
*}
* </pre>
*
*
* The default constructor is used to instantiate the library in response to
* {@code require 'hyperbolic'} statement, provided it is on Java&quot;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.
* <p>
* To test it, a script such as this can be used:
*
*
* <pre>
* {@code
* local t = require('hyperbolic')
@@ -115,7 +115,7 @@ import org.luaj.vm2.Varargs;
* </pre>
* <p>
* It should produce something like:
*
*
* <pre>
* {@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 {
* <p>
* 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 {
* <p>
* 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:

View File

@@ -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()}
*
*
* <pre>
* {
* &#64;code
@@ -62,14 +62,14 @@ import org.luaj.vm2.Varargs;
* System.out.println(globals.get("math").get("sqrt").call(LuaValue.valueOf(2)));
* }
* </pre>
*
*
* 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.
* <p>
* To instantiate and use it directly, link it into your globals table via
* {@link LuaValue#load(LuaValue)} using code such as:
*
*
* <pre>
* {
* &#64;code
@@ -80,13 +80,13 @@ import org.luaj.vm2.Varargs;
* System.out.println(globals.get("math").get("sqrt").call(LuaValue.valueOf(2)));
* }
* </pre>
*
*
* Doing so will ensure the library is properly initialized and loaded into the
* globals table.
* <p>
* 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);

View File

@@ -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;
* <p>
* 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());
}

View File

@@ -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()}
*
*
* <pre>
* {
* &#64;code
@@ -65,14 +65,14 @@ import org.luaj.vm2.Varargs;
* System.out.println(globals.get("os").get("time").call());
* }
* </pre>
*
*
* 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.
* <p>
* To instantiate and use it directly, link it into your globals table via
* {@link LuaValue#load(LuaValue)} using code such as:
*
*
* <pre>
* {
* &#64;code
@@ -84,7 +84,7 @@ import org.luaj.vm2.Varargs;
* }
* </pre>
* <p>
*
*
* @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;
}
}
}

View File

@@ -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.
*
*
* <h3>Lua Environment Variables</h3> The following variables are available to
* lua scrips when this library has been loaded:
* <ul>
@@ -44,18 +45,18 @@ import org.luaj.vm2.Varargs;
* <li><code>"package.searchers"</code> Lua table of functions that search for
* object to load.
* </ul>
*
*
* <h3>Java Environment Variables</h3> These Java environment variables affect
* the library behavior:
* <ul>
* <li><code>"luaj.package.path"</code> Initial value for
* <code>"package.path"</code>. Default value is <code>"?.lua"</code>
* </ul>
*
*
* <h3>Loading</h3> 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()}
*
*
* <pre>
* {@code
* Globals globals = JsePlatform.standardGlobals();
@@ -65,7 +66,7 @@ import org.luaj.vm2.Varargs;
* <p>
* To instantiate and use it directly, link it into your globals table via
* {@link LuaValue#load(LuaValue)} using code such as:
*
*
* <pre>
* {
* &#64;code
@@ -75,14 +76,14 @@ import org.luaj.vm2.Varargs;
* System.out.println(globals.get("require").call("foo"));
* }
* </pre>
*
*
* <h3>Limitations</h3> 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.
* <p>
*
*
* @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 '.':

View File

@@ -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;
* <p>
* The io library does not use this API for file manipulation.
* <p>
*
*
* @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);
}

View File

@@ -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()}
*
*
* <pre>
* {
* &#64;code
@@ -50,7 +50,7 @@ import org.luaj.vm2.compiler.DumpState;
* <p>
* To instantiate and use it directly, link it into your globals table via
* {@link LuaValue#load(LuaValue)} using code such as:
*
*
* <pre>
* {
* &#64;code
@@ -63,7 +63,7 @@ import org.luaj.vm2.compiler.DumpState;
* </pre>
* <p>
* 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;

View File

@@ -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.
*
*
* <p>
* 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()}
*
*
* <pre>
* {
* &#64;code
@@ -44,7 +44,7 @@ import org.luaj.vm2.Varargs;
* <p>
* To instantiate and use it directly, link it into your globals table via
* {@link LuaValue#load(LuaValue)} using code such as:
*
*
* <pre>
* {
* &#64;code
@@ -58,7 +58,7 @@ import org.luaj.vm2.Varargs;
* <p>
* 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

View File

@@ -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");
}

View File

@@ -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;
* <p>
* 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));
}

View File

@@ -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;
* <p>
* 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));
}

View File

@@ -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;
* <p>
* 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);
}

View File

@@ -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;
* <p>
* 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();
}

View File

@@ -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;
* <p>
* Typically, this library is included as part of a call to
* {@link org.luaj.vm2.lib.jme.JmePlatform#standardGlobals()}
*
*
* <pre>
* {
* &#64;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:
*
*
* <pre>
* {
* &#64;code
@@ -72,7 +72,7 @@ import org.luaj.vm2.lib.LibFunction;
* <p>
* 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 {

View File

@@ -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()}
* <p>
* A simple example of initializing globals and using them from Java is:
*
*
* <pre>
* {
* &#64;code
@@ -70,7 +68,7 @@ import org.luaj.vm2.lib.TableLib;
* </pre>
* <p>
* Once globals are created, a simple way to load and run a script is:
*
*
* <pre>
* {@code
* LoadState.load( getClass().getResourceAsStream("main.lua"), "main.lua", globals ).call();
@@ -78,13 +76,13 @@ import org.luaj.vm2.lib.TableLib;
* </pre>
* <p>
* although {@code require} could also be used:
*
*
* <pre>
* {@code
* globals.get("require").call(LuaValue.valueOf("main"));
* }
* </pre>
*
*
* 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;
* <p>
* <p>
* 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()

View File

@@ -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;

View File

@@ -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) {

View File

@@ -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)

View File

@@ -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<Stat> stats = new ArrayList<Stat>();
public List<Stat> 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);
}

View File

@@ -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

View File

@@ -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);
}

View File

@@ -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<Exp>();
this.exps = new ArrayList<>();
this.exps.add(Exp.constant(string));
}
public FuncArgs(TableConstructor table) {
this.exps = new ArrayList<Exp>();
this.exps = new ArrayList<>();
this.exps.add(table);
}

View File

@@ -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

View File

@@ -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<String>();
dots = new ArrayList<>();
dots.add(dot);
}

View File

@@ -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

View File

@@ -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<Name> 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) {

View File

@@ -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<String> LUA_KEYWORDS = new HashSet<String>();
private static final Set<String> 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<String, Variable> namedVariables = new HashMap<String, Variable>();
public final Map<String, Variable> 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;

View File

@@ -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<Name> EMPTY_NAMELIST = new ArrayList<Name>();
public static final List<Name> EMPTY_NAMELIST = new ArrayList<>();
public static final ParList EMPTY_PARLIST = new ParList(EMPTY_NAMELIST, false);
public final List<Name> names;

View File

@@ -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);
}

View File

@@ -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;

View File

@@ -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

View File

@@ -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<TableField> fields;
@Override
public void accept(Visitor visitor) {
visitor.visit(this);
}

View File

@@ -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

View File

@@ -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

View File

@@ -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<VarExp> 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<Exp> 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<Name> 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) {

View File

@@ -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

View File

@@ -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;
* <p>
* 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:

View File

@@ -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;
* <p>
* 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;

View File

@@ -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;
* <p>
* 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);

View File

@@ -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;
* <p>
* 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");

View File

@@ -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;
* <p>
* 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());

View File

@@ -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;
* <p>
* 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]);

View File

@@ -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;
* <p>
* 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");

View File

@@ -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;
* <p>
* Typically, this library is included as part of a call to
* {@link org.luaj.vm2.lib.jse.JsePlatform#standardGlobals()}
*
*
* <pre>
* {
* &#64;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:
*
*
* <pre>
* {
* &#64;code
@@ -73,7 +73,7 @@ import org.luaj.vm2.lib.ResourceFinder;
* case.
* <p>
* 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 {
* <P>
* 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())

View File

@@ -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;
* <p>
* Typically, this library is included as part of a call to
* {@link org.luaj.vm2.lib.jse.JsePlatform#standardGlobals()}
*
*
* <pre>
* {
* &#64;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:
*
*
* <pre>
* {
* &#64;code
@@ -73,7 +73,7 @@ import org.luaj.vm2.lib.LibFunction;
* <p>
* 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);
}

View File

@@ -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;
* <p>
* Typically, this library is included as part of a call to
* {@link org.luaj.vm2.lib.jse.JsePlatform#standardGlobals()}
*
*
* <pre>
* {
* &#64;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:
*
*
* <pre>
* {
* &#64;code
@@ -64,7 +64,7 @@ import org.luaj.vm2.lib.TwoArgFunction;
* <p>
* 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);
}

View File

@@ -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;
* <p>
* Typically, this library is included as part of a call to
* {@link org.luaj.vm2.lib.jse.JsePlatform#standardGlobals()}
*
*
* <pre>
* {
* &#64;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:
*
*
* <pre>
* {
* &#64;code
@@ -76,7 +76,7 @@ import org.luaj.vm2.lib.OsLib;
* However, other libraries such as <em>MathLib</em> are not loaded in this
* case.
* <p>
*
*
* @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);

View File

@@ -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()}
* <p>
* A simple example of initializing globals and using them from Java is:
*
*
* <pre>
* {
* &#64;code
@@ -52,7 +52,7 @@ import org.luaj.vm2.lib.TableLib;
* </pre>
* <p>
* Once globals are created, a simple way to load and run a script is:
*
*
* <pre>
* {@code
* globals.load( new FileInputStream("main.lua"), "main.lua" ).call();
@@ -60,13 +60,13 @@ import org.luaj.vm2.lib.TableLib;
* </pre>
* <p>
* although {@code require} could also be used:
*
*
* <pre>
* {@code
* globals.get("require").call(LuaValue.valueOf("main"));
* }
* </pre>
*
*
* 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}.
* <p>
* 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) {

View File

@@ -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];

View File

@@ -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);
}

View File

@@ -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 <a href="http://www.keplerproject.org/luajava/">luajava</a> documentation
* pages.
*
*
* <p>
* Typically, this library is included as part of a call to
* {@link org.luaj.vm2.lib.jse.JsePlatform#standardGlobals()}
*
*
* <pre>
* {
* &#64;code
@@ -60,7 +60,7 @@ import org.luaj.vm2.lib.VarArgFunction;
* <p>
* To instantiate and use it directly, link it into your globals table via
* {@link Globals#load} using code such as:
*
*
* <pre>
* {
* &#64;code
@@ -73,7 +73,7 @@ import org.luaj.vm2.lib.VarArgFunction;
* }
* </pre>
* <p>
*
*
* 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;
* <p>
* 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) {

View File

@@ -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;
}

View File

@@ -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[] {}, "<clinit>",
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<Integer, Integer> plainSlotVars = new HashMap<Integer, Integer>();
private Map<Integer, Integer> upvalueSlotVars = new HashMap<Integer, Integer>();
private Map<Integer, LocalVariableGen> localVarGenBySlot = new HashMap<Integer, LocalVariableGen>();
private final Map<Integer, Integer> plainSlotVars = new HashMap<>();
private final Map<Integer, Integer> upvalueSlotVars = new HashMap<>();
private final Map<Integer, LocalVariableGen> localVarGenBySlot = new HashMap<>();
private int findSlot(int slot, Map<Integer, Integer> 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<LuaValue, String> constants = new HashMap<LuaValue, String>();
private final Map<LuaValue, String> 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 ) {

View File

@@ -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;

View File

@@ -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<String, byte[]> unloaded = new HashMap<String, byte[]>();
private final Map<String, byte[]> 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);

View File

@@ -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;
* <p>
* To override the default compiling behavior with {@link LuaJC} lua-to-java
* bytecode compiler, install it before undumping code, for example:
*
*
* <pre>
* {@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;
}
}

View File

@@ -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();

View File

@@ -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;
}

View File

@@ -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)

Some files were not shown because too many files have changed in this diff Show More