Define clean up steps and clean up code

This commit is contained in:
Enrico Horn
2021-07-09 20:37:32 +02:00
parent 5465eff841
commit bf23883492
106 changed files with 2457 additions and 1412 deletions

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 * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -30,7 +30,7 @@ package org.luaj.vm2;
* <p> * <p>
* To convert back to a {@link LuaValue} again, the function * To convert back to a {@link LuaValue} again, the function
* {@link Buffer#value()} is used. * {@link Buffer#value()} is used.
* *
* @see LuaValue * @see LuaValue
* @see LuaValue#buffer() * @see LuaValue#buffer()
* @see LuaString * @see LuaString
@@ -57,7 +57,7 @@ public final class Buffer {
/** /**
* Create buffer with default capacity * Create buffer with default capacity
* *
* @see #DEFAULT_CAPACITY * @see #DEFAULT_CAPACITY
*/ */
public Buffer() { public Buffer() {
@@ -66,7 +66,7 @@ public final class Buffer {
/** /**
* Create buffer with specified initial capacity * Create buffer with specified initial capacity
* *
* @param initialCapacity the initial capacity * @param initialCapacity the initial capacity
*/ */
public Buffer(int initialCapacity) { public Buffer(int initialCapacity) {
@@ -78,7 +78,7 @@ public final class Buffer {
/** /**
* Create buffer with specified initial value * Create buffer with specified initial value
* *
* @param value the initial value * @param value the initial value
*/ */
public Buffer(LuaValue value) { public Buffer(LuaValue value) {
@@ -89,7 +89,7 @@ public final class Buffer {
/** /**
* Get buffer contents as a {@link LuaValue} * Get buffer contents as a {@link LuaValue}
* *
* @return value as a {@link LuaValue}, converting as necessary * @return value as a {@link LuaValue}, converting as necessary
*/ */
public LuaValue value() { public LuaValue value() {
@@ -98,7 +98,7 @@ public final class Buffer {
/** /**
* Set buffer contents as a {@link LuaValue} * Set buffer contents as a {@link LuaValue}
* *
* @param value value to set * @param value value to set
*/ */
public Buffer setvalue(LuaValue value) { public Buffer setvalue(LuaValue value) {
@@ -110,17 +110,17 @@ public final class Buffer {
/** /**
* Convert the buffer to a {@link LuaString} * Convert the buffer to a {@link LuaString}
* *
* @return the value as a {@link LuaString} * @return the value as a {@link LuaString}
*/ */
public final LuaString tostring() { public LuaString tostring() {
realloc(length, 0); realloc(length, 0);
return LuaString.valueOf(bytes, offset, length); return LuaString.valueOf(bytes, offset, length);
} }
/** /**
* Convert the buffer to a Java String * Convert the buffer to a Java String
* *
* @return the value as a Java String * @return the value as a Java String
*/ */
public String tojstring() { public String tojstring() {
@@ -129,19 +129,20 @@ public final class Buffer {
/** /**
* Convert the buffer to a Java String * Convert the buffer to a Java String
* *
* @return the value as a Java String * @return the value as a Java String
*/ */
@Override
public String toString() { public String toString() {
return tojstring(); return tojstring();
} }
/** /**
* Append a single byte to the buffer. * Append a single byte to the buffer.
* *
* @return {@code this} to allow call chaining * @return {@code this} to allow call chaining
*/ */
public final Buffer append(byte b) { public Buffer append(byte b) {
makeroom(0, 1); makeroom(0, 1);
bytes[offset+length++] = b; bytes[offset+length++] = b;
return this; return this;
@@ -149,20 +150,20 @@ public final class Buffer {
/** /**
* Append a {@link LuaValue} to the buffer. * Append a {@link LuaValue} to the buffer.
* *
* @return {@code this} to allow call chaining * @return {@code this} to allow call chaining
*/ */
public final Buffer append(LuaValue val) { public Buffer append(LuaValue val) {
append(val.strvalue()); append(val.strvalue());
return this; return this;
} }
/** /**
* Append a {@link LuaString} to the buffer. * Append a {@link LuaString} to the buffer.
* *
* @return {@code this} to allow call chaining * @return {@code this} to allow call chaining
*/ */
public final Buffer append(LuaString str) { public Buffer append(LuaString str) {
final int n = str.m_length; final int n = str.m_length;
makeroom(0, n); makeroom(0, n);
str.copyInto(0, bytes, offset+length, 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 * Append a Java String to the buffer. The Java string will be converted to
* bytes using the UTF8 encoding. * bytes using the UTF8 encoding.
* *
* @return {@code this} to allow call chaining * @return {@code this} to allow call chaining
* @see LuaString#encodeToUtf8(char[], int, byte[], int) * @see LuaString#encodeToUtf8(char[], int, byte[], int)
*/ */
public final Buffer append(String str) { public Buffer append(String str) {
char[] c = str.toCharArray(); char[] c = str.toCharArray();
final int n = LuaString.lengthAsUtf8(c); final int n = LuaString.lengthAsUtf8(c);
makeroom(0, n); makeroom(0, n);
@@ -188,7 +189,7 @@ public final class Buffer {
/** /**
* Concatenate this buffer onto a {@link LuaValue} * Concatenate this buffer onto a {@link LuaValue}
* *
* @param lhs the left-hand-side value onto which we are concatenating * @param lhs the left-hand-side value onto which we are concatenating
* {@code this} * {@code this}
* @return {@link Buffer} for use in call chaining. * @return {@link Buffer} for use in call chaining.
@@ -199,7 +200,7 @@ public final class Buffer {
/** /**
* Concatenate this buffer onto a {@link LuaString} * Concatenate this buffer onto a {@link LuaString}
* *
* @param lhs the left-hand-side value onto which we are concatenating * @param lhs the left-hand-side value onto which we are concatenating
* {@code this} * {@code this}
* @return {@link Buffer} for use in call chaining. * @return {@link Buffer} for use in call chaining.
@@ -212,7 +213,7 @@ public final class Buffer {
* Concatenate this buffer onto a {@link LuaNumber} * Concatenate this buffer onto a {@link LuaNumber}
* <p> * <p>
* The {@link LuaNumber} will be converted to a string before concatenating. * The {@link LuaNumber} will be converted to a string before concatenating.
* *
* @param lhs the left-hand-side value onto which we are concatenating * @param lhs the left-hand-side value onto which we are concatenating
* {@code this} * {@code this}
* @return {@link Buffer} for use in call chaining. * @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 * 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 * @param s the left-hand-side value which we will concatenate onto the
* front of {@code this} * front of {@code this}
* @return {@link Buffer} for use in call chaining. * @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. * Ensure there is enough room before and after the bytes.
* *
* @param nbefore number of unused bytes which must precede the data after * @param nbefore number of unused bytes which must precede the data after
* this completes * this completes
* @param nafter number of unused bytes which must follow the data after * @param nafter number of unused bytes which must follow the data after
* this completes * this completes
*/ */
public final void makeroom(int nbefore, int nafter) { public void makeroom(int nbefore, int nafter) {
if (value != null) { if (value != null) {
LuaString s = value.strvalue(); LuaString s = value.strvalue();
value = null; value = null;
@@ -263,11 +264,11 @@ public final class Buffer {
/** /**
* Reallocate the internal storage for the buffer * Reallocate the internal storage for the buffer
* *
* @param newSize the size of the buffer to use * @param newSize the size of the buffer to use
* @param newOffset the offset 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) { if (newSize != bytes.length) {
byte[] newBytes = new byte[newSize]; byte[] newBytes = new byte[newSize];
System.arraycopy(bytes, offset, newBytes, newOffset, length); 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 * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * 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 * Global environment used by luaj. Contains global variables referenced by
* executing lua. * executing lua.
* <p> * <p>
* *
* <h3>Constructing and Initializing Instances</h3> Typically, this is * <h3>Constructing and Initializing Instances</h3> Typically, this is
* constructed indirectly by a call to * constructed indirectly by a call to
* {@link org.luaj.vm2.lib.jse.JsePlatform#standardGlobals()} or * {@link org.luaj.vm2.lib.jse.JsePlatform#standardGlobals()} or
* {@link org.luaj.vm2.lib.jme.JmePlatform#standardGlobals()}, and then used to * {@link org.luaj.vm2.lib.jme.JmePlatform#standardGlobals()}, and then used to
* load lua scripts for execution as in the following example. * load lua scripts for execution as in the following example.
* *
* <pre> * <pre>
* { * {
* &#64;code * &#64;code
@@ -50,12 +50,12 @@ import org.luaj.vm2.lib.ResourceFinder;
* globals.load(new StringReader("print 'hello'"), "main.lua").call(); * globals.load(new StringReader("print 'hello'"), "main.lua").call();
* } * }
* </pre> * </pre>
* *
* The creates a complete global environment with the standard libraries loaded. * The creates a complete global environment with the standard libraries loaded.
* <p> * <p>
* For specialized circumstances, the Globals may be constructed directly and * For specialized circumstances, the Globals may be constructed directly and
* loaded with only those libraries that are needed, for example. * loaded with only those libraries that are needed, for example.
* *
* <pre> * <pre>
* { * {
* &#64;code * &#64;code
@@ -63,17 +63,17 @@ import org.luaj.vm2.lib.ResourceFinder;
* globals.load(new BaseLib()); * globals.load(new BaseLib());
* } * }
* </pre> * </pre>
* *
* <h3>Loading and Executing Lua Code</h3> Globals contains convenience * <h3>Loading and Executing Lua Code</h3> Globals contains convenience
* functions to load and execute lua source code given a Reader. A simple * functions to load and execute lua source code given a Reader. A simple
* example is: * example is:
* *
* <pre> * <pre>
* {@code * {@code
* globals.load( new StringReader("print 'hello'"), "main.lua" ).call(); * globals.load( new StringReader("print 'hello'"), "main.lua" ).call();
* } * }
* </pre> * </pre>
* *
* <h3>Fine-Grained Control of Compiling and Loading Lua</h3> Executable * <h3>Fine-Grained Control of Compiling and Loading Lua</h3> Executable
* LuaFunctions are created from lua code in several steps * LuaFunctions are created from lua code in several steps
* <ul> * <ul>
@@ -92,7 +92,7 @@ import org.luaj.vm2.lib.ResourceFinder;
* <li>convert lua bytecode to equivalent Java bytecode using * <li>convert lua bytecode to equivalent Java bytecode using
* {@link org.luaj.vm2.luajc.LuaJC} that implements {@link Loader} directly * {@link org.luaj.vm2.luajc.LuaJC} that implements {@link Loader} directly
* </ul> * </ul>
* *
* <h3>Java Field</h3> Certain public fields are provided that contain the * <h3>Java Field</h3> Certain public fields are provided that contain the
* current values of important global state: * current values of important global state:
* <ul> * <ul>
@@ -107,7 +107,7 @@ import org.luaj.vm2.lib.ResourceFinder;
* <li>{@link #undumper} Current loaded {@link Undumper}, if any. * <li>{@link #undumper} Current loaded {@link Undumper}, if any.
* <li>{@link #loader} Current loaded {@link Loader}, if any. * <li>{@link #loader} Current loaded {@link Loader}, if any.
* </ul> * </ul>
* *
* <h3>Lua Environment Variables</h3> When using * <h3>Lua Environment Variables</h3> When using
* {@link org.luaj.vm2.lib.jse.JsePlatform} or * {@link org.luaj.vm2.lib.jse.JsePlatform} or
* {@link org.luaj.vm2.lib.jme.JmePlatform}, these environment variables are * {@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>"_G" Pointer to this Globals.
* <li>"_VERSION" String containing the version of luaj. * <li>"_VERSION" String containing the version of luaj.
* </ul> * </ul>
* *
* <h3>Use in Multithreaded Environments</h3> In a multi-threaded server * <h3>Use in Multithreaded Environments</h3> In a multi-threaded server
* environment, each server thread should create one Globals instance, which * environment, each server thread should create one Globals instance, which
* will be logically distinct and not interfere with each other, but share * will be logically distinct and not interfere with each other, but share
* certain static immutable resources such as class data and string data. * certain static immutable resources such as class data and string data.
* <p> * <p>
* *
* @see org.luaj.vm2.lib.jse.JsePlatform * @see org.luaj.vm2.lib.jse.JsePlatform
* @see org.luaj.vm2.lib.jme.JmePlatform * @see org.luaj.vm2.lib.jme.JmePlatform
* @see LuaValue * @see LuaValue
@@ -195,27 +195,28 @@ public class Globals extends LuaTable {
* Check that this object is a Globals object, and return it, otherwise * Check that this object is a Globals object, and return it, otherwise
* throw an error. * throw an error.
*/ */
@Override
public Globals checkglobals() { public Globals checkglobals() {
return this; return this;
} }
/** /**
* The installed loader. * The installed loader.
* *
* @see Loader * @see Loader
*/ */
public Loader loader; public Loader loader;
/** /**
* The installed compiler. * The installed compiler.
* *
* @see Compiler * @see Compiler
*/ */
public Compiler compiler; public Compiler compiler;
/** /**
* The installed undumper. * The installed undumper.
* *
* @see Undumper * @see Undumper
*/ */
public Undumper 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 * Convenience function for loading a file that is either binary lua or lua
* source. * source.
* *
* @param filename Name of the file to load. * @param filename Name of the file to load.
* @return LuaValue that can be call()'ed or invoke()'ed. * @return LuaValue that can be call()'ed or invoke()'ed.
* @throws LuaError if the file could not be loaded. * @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 * Convenience function to load a string value as a script. Must be lua
* source. * source.
* *
* @param script Contents of a lua script, such as "print 'hello, * @param script Contents of a lua script, such as "print 'hello,
* world.'" * world.'"
* @param chunkname Name that will be used within the chunk as the source. * @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 * Convenience function to load a string value as a script. Must be lua
* source. * source.
* *
* @param script Contents of a lua script, such as "print 'hello, world.'" * @param script Contents of a lua script, such as "print 'hello, world.'"
* @return LuaValue that may be executed via .call(), .invoke(), or * @return LuaValue that may be executed via .call(), .invoke(), or
* .method() calls. * .method() calls.
@@ -267,7 +268,7 @@ public class Globals extends LuaTable {
/** /**
* Convenience function to load a string value as a script with a custom * Convenience function to load a string value as a script with a custom
* environment. Must be lua source. * environment. Must be lua source.
* *
* @param script Contents of a lua script, such as "print 'hello, * @param script Contents of a lua script, such as "print 'hello,
* world.'" * world.'"
* @param chunkname Name that will be used within the chunk as the source. * @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 * 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 * source is converted to UTF-8, so any characters appearing in quoted
* literals above the range 128 will be converted into multiple bytes. * literals above the range 128 will be converted into multiple bytes.
* *
* @param reader Reader containing text of a lua script, such as "print * @param reader Reader containing text of a lua script, such as "print
* 'hello, world.'" * 'hello, world.'"
* @param chunkname Name that will be used within the chunk as the source. * @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 * 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 * characters appearing in quoted literals above the range 128 will be
* converted into multiple bytes. * converted into multiple bytes.
* *
* @param reader Reader containing text of a lua script, such as "print * @param reader Reader containing text of a lua script, such as "print
* 'hello, world.'" * 'hello, world.'"
* @param chunkname Name that will be used within the chunk as the source. * @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. * 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 is InputStream containing a lua script or compiled lua"
* @param chunkname Name that will be used within the chunk as the source. * @param chunkname Name that will be used within the chunk as the source.
* @param mode String containing 'b' or 't' or both to control * @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 * 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 * chunk signature, or a text input file. If it is a text input file, it is
* interpreted as a UTF-8 byte sequence. * interpreted as a UTF-8 byte sequence.
* *
* @param is Input stream containing a lua script or compiled lua" * @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 chunkname Name that will be used within the chunk as the source.
* @param mode String containing 'b' or 't' or both to control loading * @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. * Function which yields the current thread.
* *
* @param args Arguments to supply as return values in the resume function * @param args Arguments to supply as return values in the resume function
* of the resuming thread. * of the resuming thread.
* @return Values supplied as arguments to the resume() call that * @return Values supplied as arguments to the resume() call that
@@ -415,14 +416,17 @@ public class Globals extends LuaTable {
n = s.length(); n = s.length();
} }
@Override
public void close() throws IOException { public void close() throws IOException {
i = n; i = n;
} }
@Override
public int read() throws IOException { public int read() throws IOException {
return i < n? s.charAt(i++): -1; return i < n? s.charAt(i++): -1;
} }
@Override
public int read(char[] cbuf, int off, int len) throws IOException { public int read(char[] cbuf, int off, int len) throws IOException {
int j = 0; int j = 0;
for (; j < len && i < n; ++j, ++i) for (; j < len && i < n; ++j, ++i)
@@ -444,15 +448,18 @@ public class Globals extends LuaTable {
abstract protected int avail() throws IOException; abstract protected int avail() throws IOException;
@Override
public int read() throws IOException { public int read() throws IOException {
int a = avail(); 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 { public int read(byte[] b) throws IOException {
return read(b, 0, b.length); return read(b, 0, b.length);
} }
@Override
public int read(byte[] b, int i0, int n) throws IOException { public int read(byte[] b, int i0, int n) throws IOException {
int a = avail(); int a = avail();
if (a <= 0) if (a <= 0)
@@ -463,12 +470,14 @@ public class Globals extends LuaTable {
return n_read; return n_read;
} }
@Override
public long skip(long n) throws IOException { public long skip(long n) throws IOException {
final long k = Math.min(n, j-i); final long k = Math.min(n, j-i);
i += k; i += k;
return k; return k;
} }
@Override
public int available() throws IOException { public int available() throws IOException {
return j-i; return j-i;
} }
@@ -488,6 +497,7 @@ public class Globals extends LuaTable {
this.r = r; this.r = r;
} }
@Override
protected int avail() throws IOException { protected int avail() throws IOException {
if (i < j) if (i < j)
return j-i; return j-i;
@@ -505,6 +515,7 @@ public class Globals extends LuaTable {
return j; return j;
} }
@Override
public void close() throws IOException { public void close() throws IOException {
r.close(); r.close();
} }
@@ -529,6 +540,7 @@ public class Globals extends LuaTable {
this.s = s; this.s = s;
} }
@Override
protected int avail() throws IOException { protected int avail() throws IOException {
if (i < j) if (i < j)
return j-i; return j-i;
@@ -549,10 +561,12 @@ public class Globals extends LuaTable {
return n; return n;
} }
@Override
public void close() throws IOException { public void close() throws IOException {
s.close(); s.close();
} }
@Override
public synchronized void mark(int n) { public synchronized void mark(int n) {
if (i > 0 || n > b.length) { if (i > 0 || n > b.length) {
byte[] dest = n > b.length? new byte[n]: b; byte[] dest = n > b.length? new byte[n]: b;
@@ -563,10 +577,12 @@ public class Globals extends LuaTable {
} }
} }
@Override
public boolean markSupported() { public boolean markSupported() {
return true; return true;
} }
@Override
public synchronized void reset() throws IOException { public synchronized void reset() throws IOException {
i = 0; i = 0;
} }

View File

@@ -10,7 +10,7 @@
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -35,7 +35,7 @@ import java.io.InputStream;
* <p> * <p>
* The canonical method to load and execute code is done indirectly using the * The canonical method to load and execute code is done indirectly using the
* Globals: * Globals:
* *
* <pre> * <pre>
* { * {
* &#64;code * &#64;code
@@ -44,7 +44,7 @@ import java.io.InputStream;
* chunk.call(); * chunk.call();
* } * }
* </pre> * </pre>
* *
* This should work regardless of which {@link Globals.Compiler} or * This should work regardless of which {@link Globals.Compiler} or
* {@link Globals.Undumper} have been installed. * {@link Globals.Undumper} have been installed.
* <p> * <p>
@@ -53,10 +53,10 @@ import java.io.InputStream;
* {@link LoadState} default undumper is installed as the default * {@link LoadState} default undumper is installed as the default
* {@link Globals.Undumper}. * {@link Globals.Undumper}.
* <p> * <p>
* *
* A lua binary file is created via the {@link org.luaj.vm2.compiler.DumpState} * A lua binary file is created via the {@link org.luaj.vm2.compiler.DumpState}
* class : * class :
* *
* <pre> * <pre>
* { * {
* &#64;code * &#64;code
@@ -67,10 +67,10 @@ import java.io.InputStream;
* byte[] lua_binary_file_bytes = o.toByteArray(); * byte[] lua_binary_file_bytes = o.toByteArray();
* } * }
* </pre> * </pre>
* *
* The {@link LoadState}'s default undumper {@link #instance} may be used * The {@link LoadState}'s default undumper {@link #instance} may be used
* directly to undump these bytes: * directly to undump these bytes:
* *
* <pre> * <pre>
* {@code * {@code
* Prototypep = LoadState.instance.undump(new ByteArrayInputStream(lua_binary_file_bytes), "main.lua"); * Prototypep = LoadState.instance.undump(new ByteArrayInputStream(lua_binary_file_bytes), "main.lua");
@@ -78,10 +78,10 @@ import java.io.InputStream;
* c.call(); * c.call();
* } * }
* </pre> * </pre>
* *
* *
* More commonly, the {@link Globals.Undumper} may be used to undump them: * More commonly, the {@link Globals.Undumper} may be used to undump them:
* *
* <pre> * <pre>
* { * {
* &#64;code * &#64;code
@@ -90,7 +90,7 @@ import java.io.InputStream;
* c.call(); * c.call();
* } * }
* </pre> * </pre>
* *
* @see Globals.Compiler * @see Globals.Compiler
* @see Globals.Undumper * @see Globals.Undumper
* @see LuaClosure * @see LuaClosure
@@ -124,8 +124,8 @@ public class LoadState {
public static final int NUMBER_FORMAT_NUM_PATCH_INT32 = 4; public static final int NUMBER_FORMAT_NUM_PATCH_INT32 = 4;
// type constants // type constants
public static final int LUA_TINT = (-2); public static final int LUA_TINT = -2;
public static final int LUA_TNONE = (-1); public static final int LUA_TNONE = -1;
public static final int LUA_TNIL = 0; public static final int LUA_TNIL = 0;
public static final int LUA_TBOOLEAN = 1; public static final int LUA_TBOOLEAN = 1;
public static final int LUA_TLIGHTUSERDATA = 2; public static final int LUA_TLIGHTUSERDATA = 2;
@@ -196,18 +196,18 @@ public class LoadState {
/** /**
* Load a 4-byte int value from the input stream * Load a 4-byte int value from the input stream
* *
* @return the int value laoded. * @return the int value laoded.
**/ **/
int loadInt() throws IOException { int loadInt() throws IOException {
is.readFully(buf, 0, 4); is.readFully(buf, 0, 4);
return luacLittleEndian? (buf[3]<<24) | ((0xff & buf[2])<<16) | ((0xff & buf[1])<<8) | (0xff & buf[0]) 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]); : buf[0]<<24 | (0xff & buf[1])<<16 | (0xff & buf[2])<<8 | 0xff & buf[3];
} }
/** /**
* Load an array of int values from the input stream * Load an array of int values from the input stream
* *
* @return the array of int values laoded. * @return the array of int values laoded.
**/ **/
int[] loadIntArray() throws IOException { int[] loadIntArray() throws IOException {
@@ -222,16 +222,15 @@ public class LoadState {
is.readFully(buf, 0, m); is.readFully(buf, 0, m);
int[] array = new int[n]; int[] array = new int[n];
for (int i = 0, j = 0; i < n; ++i, j += 4) for (int i = 0, j = 0; i < n; ++i, j += 4)
array[i] = luacLittleEndian array[i] = luacLittleEndian? buf[j+3]<<24 | (0xff & buf[j+2])<<16 | (0xff & buf[j+1])<<8 | 0xff & buf[j+0]
? (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];
: (buf[j+0]<<24) | ((0xff & buf[j+1])<<16) | ((0xff & buf[j+2])<<8) | (0xff & buf[j+3]);
return array; return array;
} }
/** /**
* Load a long value from the input stream * Load a long value from the input stream
* *
* @return the long value laoded. * @return the long value laoded.
**/ **/
long loadInt64() throws IOException { long loadInt64() throws IOException {
@@ -243,12 +242,12 @@ public class LoadState {
b = loadInt(); b = loadInt();
a = 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 * Load a lua strin gvalue from the input stream
* *
* @return the {@link LuaString} value laoded. * @return the {@link LuaString} value laoded.
**/ **/
LuaString loadString() throws IOException { LuaString loadString() throws IOException {
@@ -262,25 +261,25 @@ public class LoadState {
/** /**
* Convert bits in a long value to a {@link LuaValue}. * Convert bits in a long value to a {@link LuaValue}.
* *
* @param bits long value containing the bits * @param bits long value containing the bits
* @return {@link LuaInteger} or {@link LuaDouble} whose value corresponds * @return {@link LuaInteger} or {@link LuaDouble} whose value corresponds
* to the bits provided. * to the bits provided.
*/ */
public static LuaValue longBitsToLuaNumber(long bits) { public static LuaValue longBitsToLuaNumber(long bits) {
if ((bits & ((1L<<63)-1)) == 0L) { if ((bits & (1L<<63)-1) == 0L) {
return LuaValue.ZERO; return LuaValue.ZERO;
} }
int e = (int) ((bits>>52) & 0x7ffL)-1023; int e = (int) (bits>>52 & 0x7ffL)-1023;
if (e >= 0 && e < 31) { if (e >= 0 && e < 31) {
long f = bits & 0xFFFFFFFFFFFFFL; long f = bits & 0xFFFFFFFFFFFFFL;
int shift = 52-e; int shift = 52-e;
long intPrecMask = (1L<<shift)-1; long intPrecMask = (1L<<shift)-1;
if ((f & intPrecMask) == 0) { if ((f & intPrecMask) == 0) {
int intValue = (int) (f>>shift) | (1<<e); int intValue = (int) (f>>shift) | 1<<e;
return LuaInteger.valueOf(((bits>>63) != 0)? -intValue: intValue); return LuaInteger.valueOf(bits>>63 != 0? -intValue: intValue);
} }
} }
@@ -289,7 +288,7 @@ public class LoadState {
/** /**
* Load a number from a binary chunk * Load a number from a binary chunk
* *
* @return the {@link LuaValue} loaded * @return the {@link LuaValue} loaded
* @throws IOException if an i/o exception occurs * @throws IOException if an i/o exception occurs
*/ */
@@ -303,7 +302,7 @@ public class LoadState {
/** /**
* Load a list of constants from a binary chunk * Load a list of constants from a binary chunk
* *
* @param f the function prototype * @param f the function prototype
* @throws IOException if an i/o exception occurs * @throws IOException if an i/o exception occurs
*/ */
@@ -316,7 +315,7 @@ public class LoadState {
values[i] = LuaValue.NIL; values[i] = LuaValue.NIL;
break; break;
case LUA_TBOOLEAN: case LUA_TBOOLEAN:
values[i] = (0 != is.readUnsignedByte()? LuaValue.TRUE: LuaValue.FALSE); values[i] = 0 != is.readUnsignedByte()? LuaValue.TRUE: LuaValue.FALSE;
break; break;
case LUA_TINT: case LUA_TINT:
values[i] = LuaInteger.valueOf(loadInt()); values[i] = LuaInteger.valueOf(loadInt());
@@ -345,14 +344,14 @@ public class LoadState {
f.upvalues = n > 0? new Upvaldesc[n]: NOUPVALDESCS; f.upvalues = n > 0? new Upvaldesc[n]: NOUPVALDESCS;
for (int i = 0; i < n; i++) { for (int i = 0; i < n; i++) {
boolean instack = is.readByte() != 0; boolean instack = is.readByte() != 0;
int idx = ((int) is.readByte()) & 0xff; int idx = is.readByte() & 0xff;
f.upvalues[i] = new Upvaldesc(null, instack, idx); f.upvalues[i] = new Upvaldesc(null, instack, idx);
} }
} }
/** /**
* Load the debug info for a function prototype * Load the debug info for a function prototype
* *
* @param f the function Prototype * @param f the function Prototype
* @throws IOException if there is an i/o exception * @throws IOException if there is an i/o exception
*/ */
@@ -375,7 +374,7 @@ public class LoadState {
/** /**
* Load a function prototype from the input stream * Load a function prototype from the input stream
* *
* @param p name of the source * @param p name of the source
* @return {@link Prototype} instance that was loaded * @return {@link Prototype} instance that was loaded
* @throws IOException * @throws IOException
@@ -406,13 +405,13 @@ public class LoadState {
/** /**
* Load the lua chunk header values. * Load the lua chunk header values.
* *
* @throws IOException if an i/o exception occurs. * @throws IOException if an i/o exception occurs.
*/ */
public void loadHeader() throws IOException { public void loadHeader() throws IOException {
luacVersion = is.readByte(); luacVersion = is.readByte();
luacFormat = is.readByte(); luacFormat = is.readByte();
luacLittleEndian = (0 != is.readByte()); luacLittleEndian = 0 != is.readByte();
luacSizeofInt = is.readByte(); luacSizeofInt = is.readByte();
luacSizeofSizeT = is.readByte(); luacSizeofSizeT = is.readByte();
luacSizeofInstruction = 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 * Load input stream as a lua binary chunk if the first 4 bytes are the lua
* binary signature. * binary signature.
* *
* @param stream InputStream to read, after having read the first byte * @param stream InputStream to read, after having read the first byte
* already * already
* @param chunkname Name to apply to the loaded chunk * @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 * Construct a source name from a supplied chunk name
* *
* @param name String name that appears in the chunk * @param name String name that appears in the chunk
* @return source file name * @return source file name
*/ */
@@ -479,6 +478,7 @@ public class LoadState {
} }
private static final class GlobalsUndumper implements Globals.Undumper { private static final class GlobalsUndumper implements Globals.Undumper {
@Override
public Prototype undump(InputStream stream, String chunkname) throws IOException { public Prototype undump(InputStream stream, String chunkname) throws IOException {
return LoadState.undump(stream, chunkname); return LoadState.undump(stream, chunkname);
} }

View File

@@ -10,7 +10,7 @@
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -37,7 +37,7 @@ public class LocVars {
/** /**
* Construct a LocVars instance. * Construct a LocVars instance.
* *
* @param varname The local variable name * @param varname The local variable name
* @param startpc The instruction offset when the variable comes into scope * @param startpc The instruction offset when the variable comes into scope
* @param endpc The instruction offset when the variable goes out of 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 * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * 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_C = 9;
public static final int SIZE_B = 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_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 SIZE_OP = 6;
public static final int POS_OP = 0; public static final int POS_OP = 0;
public static final int POS_A = (POS_OP+SIZE_OP); 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_C = POS_A+SIZE_A;
public static final int POS_B = (POS_C+SIZE_C); public static final int POS_B = POS_C+SIZE_C;
public static final int POS_Bx = POS_C; public static final int POS_Bx = POS_C;
public static final int POS_Ax = POS_A; public static final int POS_Ax = POS_A;
public static final int MAX_OP = ((1<<SIZE_OP)-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_A = (1<<SIZE_A)-1;
public static final int MAXARG_B = ((1<<SIZE_B)-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_C = (1<<SIZE_C)-1;
public static final int MAXARG_Bx = ((1<<SIZE_Bx)-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_sBx = MAXARG_Bx>>1; /* `sBx' is signed */
public static final int MAXARG_Ax = ((1<<SIZE_Ax)-1); 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_OP = (1<<SIZE_OP)-1<<POS_OP;
public static final int MASK_A = ((1<<SIZE_A)-1)<<POS_A; 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_B = (1<<SIZE_B)-1<<POS_B;
public static final int MASK_C = ((1<<SIZE_C)-1)<<POS_C; 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_Bx = (1<<SIZE_Bx)-1<<POS_Bx;
public static final int MASK_Ax = ((1<<SIZE_Ax)-1)<<POS_Ax; 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_OP = ~MASK_OP;
public static final int MASK_NOT_A = ~MASK_A; public static final int MASK_NOT_A = ~MASK_A;
@@ -102,31 +102,31 @@ public class Lua {
** the following macros help to manipulate instructions ** the following macros help to manipulate instructions
*/ */
public static int GET_OPCODE(int i) { 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) { 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) { 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) { 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) { 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) { 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) { 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) */ /** 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 */ /** test whether value is a constant */
public static boolean ISK(int x) { public static boolean ISK(int x) {
return 0 != ((x) & BITRK); return 0 != (x & BITRK);
} }
/** gets the index of the constant */ /** gets the index of the constant */
public static int INDEXK(int r) { 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 */ /** code a constant index as a RK value */
public static int RKASK(int x) { 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 = { public static final int[] luaP_opmodes = {
/* T A B C mode opcode */ /* T A B C mode opcode */
(0<<7) | (1<<6) | (OpArgR<<4) | (OpArgN<<2) | (iABC), /* OP_MOVE */ 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 | OpArgK<<4 | OpArgN<<2 | iABx, /* OP_LOADK */
(0<<7) | (1<<6) | (OpArgN<<4) | (OpArgN<<2) | (iABx), /* OP_LOADKX */ 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 | 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_LOADNIL */
(0<<7) | (1<<6) | (OpArgU<<4) | (OpArgN<<2) | (iABC), /* OP_GETUPVAL */ 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 | OpArgU<<4 | OpArgK<<2 | iABC, /* OP_GETTABUP */
(0<<7) | (1<<6) | (OpArgR<<4) | (OpArgK<<2) | (iABC), /* OP_GETTABLE */ 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 | OpArgK<<4 | OpArgK<<2 | iABC, /* OP_SETTABUP */
(0<<7) | (0<<6) | (OpArgU<<4) | (OpArgN<<2) | (iABC), /* OP_SETUPVAL */ 0<<7 | 0<<6 | OpArgU<<4 | OpArgN<<2 | iABC, /* OP_SETUPVAL */
(0<<7) | (0<<6) | (OpArgK<<4) | (OpArgK<<2) | (iABC), /* OP_SETTABLE */ 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 | OpArgU<<4 | OpArgU<<2 | iABC, /* OP_NEWTABLE */
(0<<7) | (1<<6) | (OpArgR<<4) | (OpArgK<<2) | (iABC), /* OP_SELF */ 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_ADD */
(0<<7) | (1<<6) | (OpArgK<<4) | (OpArgK<<2) | (iABC), /* OP_SUB */ 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_MUL */
(0<<7) | (1<<6) | (OpArgK<<4) | (OpArgK<<2) | (iABC), /* OP_DIV */ 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_MOD */
(0<<7) | (1<<6) | (OpArgK<<4) | (OpArgK<<2) | (iABC), /* OP_POW */ 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_UNM */
(0<<7) | (1<<6) | (OpArgR<<4) | (OpArgN<<2) | (iABC), /* OP_NOT */ 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 | OpArgN<<2 | iABC, /* OP_LEN */
(0<<7) | (1<<6) | (OpArgR<<4) | (OpArgR<<2) | (iABC), /* OP_CONCAT */ 0<<7 | 1<<6 | OpArgR<<4 | OpArgR<<2 | iABC, /* OP_CONCAT */
(0<<7) | (0<<6) | (OpArgR<<4) | (OpArgN<<2) | (iAsBx), /* OP_JMP */ 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_EQ */
(1<<7) | (0<<6) | (OpArgK<<4) | (OpArgK<<2) | (iABC), /* OP_LT */ 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 | OpArgK<<4 | OpArgK<<2 | iABC, /* OP_LE */
(1<<7) | (0<<6) | (OpArgN<<4) | (OpArgU<<2) | (iABC), /* OP_TEST */ 1<<7 | 0<<6 | OpArgN<<4 | OpArgU<<2 | iABC, /* OP_TEST */
(1<<7) | (1<<6) | (OpArgR<<4) | (OpArgU<<2) | (iABC), /* OP_TESTSET */ 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_CALL */
(0<<7) | (1<<6) | (OpArgU<<4) | (OpArgU<<2) | (iABC), /* OP_TAILCALL */ 0<<7 | 1<<6 | OpArgU<<4 | OpArgU<<2 | iABC, /* OP_TAILCALL */
(0<<7) | (0<<6) | (OpArgU<<4) | (OpArgN<<2) | (iABC), /* OP_RETURN */ 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_FORLOOP */
(0<<7) | (1<<6) | (OpArgR<<4) | (OpArgN<<2) | (iAsBx), /* OP_FORPREP */ 0<<7 | 1<<6 | OpArgR<<4 | OpArgN<<2 | iAsBx, /* OP_FORPREP */
(0<<7) | (0<<6) | (OpArgN<<4) | (OpArgU<<2) | (iABC), /* OP_TFORCALL */ 0<<7 | 0<<6 | OpArgN<<4 | OpArgU<<2 | iABC, /* OP_TFORCALL */
(1<<7) | (1<<6) | (OpArgR<<4) | (OpArgN<<2) | (iAsBx), /* OP_TFORLOOP */ 1<<7 | 1<<6 | OpArgR<<4 | OpArgN<<2 | iAsBx, /* OP_TFORLOOP */
(0<<7) | (0<<6) | (OpArgU<<4) | (OpArgU<<2) | (iABC), /* OP_SETLIST */ 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 | iABx, /* OP_CLOSURE */
(0<<7) | (1<<6) | (OpArgU<<4) | (OpArgN<<2) | (iABC), /* OP_VARARG */ 0<<7 | 1<<6 | OpArgU<<4 | OpArgN<<2 | iABC, /* OP_VARARG */
(0<<7) | (0<<6) | (OpArgU<<4) | (OpArgU<<2) | (iAx), /* OP_EXTRAARG */ 0<<7 | 0<<6 | OpArgU<<4 | OpArgU<<2 | iAx, /* OP_EXTRAARG */
}; };
public static int getOpMode(int m) { public static int getOpMode(int m) {
@@ -319,19 +319,19 @@ public class Lua {
} }
public static int getBMode(int m) { public static int getBMode(int m) {
return (luaP_opmodes[m]>>4) & 3; return luaP_opmodes[m]>>4 & 3;
} }
public static int getCMode(int m) { public static int getCMode(int m) {
return (luaP_opmodes[m]>>2) & 3; return luaP_opmodes[m]>>2 & 3;
} }
public static boolean testAMode(int m) { 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) { 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 */ /* 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 * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * 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 * Any {@link LuaValue} can be converted to its equivalent boolean
* representation using {@link LuaValue#toboolean()} * representation using {@link LuaValue#toboolean()}
* <p> * <p>
* *
* @see LuaValue * @see LuaValue
* @see LuaValue#valueOf(boolean) * @see LuaValue#valueOf(boolean)
* @see LuaValue#TRUE * @see LuaValue#TRUE
@@ -57,47 +57,56 @@ public final class LuaBoolean extends LuaValue {
this.v = b; this.v = b;
} }
@Override
public int type() { public int type() {
return LuaValue.TBOOLEAN; return LuaValue.TBOOLEAN;
} }
@Override
public String typename() { public String typename() {
return "boolean"; return "boolean";
} }
@Override
public boolean isboolean() { public boolean isboolean() {
return true; return true;
} }
@Override
public LuaValue not() { public LuaValue not() {
return v? FALSE: LuaValue.TRUE; return v? FALSE: LuaValue.TRUE;
} }
/** /**
* Return the boolean value for this boolean * Return the boolean value for this boolean
* *
* @return value as a Java boolean * @return value as a Java boolean
*/ */
public boolean booleanValue() { public boolean booleanValue() {
return v; return v;
} }
@Override
public boolean toboolean() { public boolean toboolean() {
return v; return v;
} }
@Override
public String tojstring() { public String tojstring() {
return v? "true": "false"; return v? "true": "false";
} }
@Override
public boolean optboolean(boolean defval) { public boolean optboolean(boolean defval) {
return this.v; return this.v;
} }
@Override
public boolean checkboolean() { public boolean checkboolean() {
return v; return v;
} }
@Override
public LuaValue getmetatable() { public LuaValue getmetatable() {
return s_metatable; return s_metatable;
} }

View File

@@ -10,7 +10,7 @@
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * 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} to use as an environment for execution. Normally the
* {@link LuaValue} is a {@link Globals} in which case the environment will * {@link LuaValue} is a {@link Globals} in which case the environment will
* contain standard lua libraries. * contain standard lua libraries.
* *
* <p> * <p>
* There are three main ways {@link LuaClosure} instances are created: * There are three main ways {@link LuaClosure} instances are created:
* <ul> * <ul>
@@ -43,7 +43,7 @@ import org.luaj.vm2.lib.DebugLib.CallFrame;
* <p> * <p>
* To construct it directly, the {@link Prototype} is typically created via a * To construct it directly, the {@link Prototype} is typically created via a
* compiler such as {@link org.luaj.vm2.compiler.LuaC}: * compiler such as {@link org.luaj.vm2.compiler.LuaC}:
* *
* <pre> * <pre>
* { * {
* &#64;code * &#64;code
@@ -58,7 +58,7 @@ import org.luaj.vm2.lib.DebugLib.CallFrame;
* <p> * <p>
* To construct it indirectly, the {@link Globals#load(java.io.Reader, String)} * To construct it indirectly, the {@link Globals#load(java.io.Reader, String)}
* method may be used: * method may be used:
* *
* <pre> * <pre>
* { * {
* &#64;code * &#64;code
@@ -87,7 +87,7 @@ import org.luaj.vm2.lib.DebugLib.CallFrame;
* <li>{@link LuaValue#invokemethod(String,Varargs)}</li> * <li>{@link LuaValue#invokemethod(String,Varargs)}</li>
* <li>...</li> * <li>...</li>
* </ul> * </ul>
* *
* @see LuaValue * @see LuaValue
* @see LuaFunction * @see LuaFunction
* @see LuaValue#isclosure() * @see LuaValue#isclosure()
@@ -97,7 +97,7 @@ import org.luaj.vm2.lib.DebugLib.CallFrame;
* @see Globals#compiler * @see Globals#compiler
*/ */
public class LuaClosure extends LuaFunction { public class LuaClosure extends LuaFunction {
private static final UpValue[] NOUPVALUES = new UpValue[0]; private static final UpValue[] NOUPVALUES = {};
public final Prototype p; 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 * Create a closure around a Prototype with a specific environment. If the
* prototype has upvalues, the environment will be written into the first * prototype has upvalues, the environment will be written into the first
* upvalue. * upvalue.
* *
* @param p the Prototype to construct this Closure for. * @param p the Prototype to construct this Closure for.
* @param env the environment to associate with the closure. * @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; globals = env instanceof Globals? (Globals) env: null;
} }
@Override
public void initupvalue1(LuaValue env) { public void initupvalue1(LuaValue env) {
if (p.upvalues == null || p.upvalues.length == 0) if (p.upvalues == null || p.upvalues.length == 0)
this.upValues = NOUPVALUES; this.upValues = NOUPVALUES;
@@ -128,18 +129,22 @@ public class LuaClosure extends LuaFunction {
} }
} }
@Override
public boolean isclosure() { public boolean isclosure() {
return true; return true;
} }
@Override
public LuaClosure optclosure(LuaClosure defval) { public LuaClosure optclosure(LuaClosure defval) {
return this; return this;
} }
@Override
public LuaClosure checkclosure() { public LuaClosure checkclosure() {
return this; return this;
} }
@Override
public String tojstring() { public String tojstring() {
return "function: " + p.toString(); return "function: " + p.toString();
} }
@@ -151,11 +156,13 @@ public class LuaClosure extends LuaFunction {
return stack; return stack;
} }
@Override
public final LuaValue call() { public final LuaValue call() {
LuaValue[] stack = getNewStack(); LuaValue[] stack = getNewStack();
return execute(stack, NONE).arg1(); return execute(stack, NONE).arg1();
} }
@Override
public final LuaValue call(LuaValue arg) { public final LuaValue call(LuaValue arg) {
LuaValue[] stack = getNewStack(); LuaValue[] stack = getNewStack();
switch (p.numparams) { switch (p.numparams) {
@@ -167,6 +174,7 @@ public class LuaClosure extends LuaFunction {
} }
} }
@Override
public final LuaValue call(LuaValue arg1, LuaValue arg2) { public final LuaValue call(LuaValue arg1, LuaValue arg2) {
LuaValue[] stack = getNewStack(); LuaValue[] stack = getNewStack();
switch (p.numparams) { switch (p.numparams) {
@@ -182,6 +190,7 @@ public class LuaClosure extends LuaFunction {
} }
} }
@Override
public final LuaValue call(LuaValue arg1, LuaValue arg2, LuaValue arg3) { public final LuaValue call(LuaValue arg1, LuaValue arg2, LuaValue arg3) {
LuaValue[] stack = getNewStack(); LuaValue[] stack = getNewStack();
switch (p.numparams) { switch (p.numparams) {
@@ -202,10 +211,12 @@ public class LuaClosure extends LuaFunction {
} }
} }
@Override
public final Varargs invoke(Varargs varargs) { public final Varargs invoke(Varargs varargs) {
return onInvoke(varargs).eval(); return onInvoke(varargs).eval();
} }
@Override
public final Varargs onInvoke(Varargs varargs) { public final Varargs onInvoke(Varargs varargs) {
LuaValue[] stack = getNewStack(); LuaValue[] stack = getNewStack();
for (int i = 0; i < p.numparams; i++) for (int i = 0; i < p.numparams; i++)
@@ -237,7 +248,7 @@ public class LuaClosure extends LuaFunction {
// pull out instruction // pull out instruction
i = code[pc]; i = code[pc];
a = ((i>>6) & 0xff); a = i>>6 & 0xff;
// process the op code // process the op code
switch (i & 0x3f) { switch (i & 0x3f) {
@@ -262,8 +273,8 @@ public class LuaClosure extends LuaFunction {
continue; continue;
case Lua.OP_LOADBOOL:/* A B C R(A):= (Bool)B: if (C) pc++ */ case Lua.OP_LOADBOOL:/* A B C R(A):= (Bool)B: if (C) pc++ */
stack[a] = (i>>>23 != 0)? LuaValue.TRUE: LuaValue.FALSE; stack[a] = i>>>23 != 0? LuaValue.TRUE: LuaValue.FALSE;
if ((i & (0x1ff<<14)) != 0) if ((i & 0x1ff<<14) != 0)
++pc; /* skip next instruction (if C) */ ++pc; /* skip next instruction (if C) */
continue; continue;
@@ -277,16 +288,16 @@ public class LuaClosure extends LuaFunction {
continue; continue;
case Lua.OP_GETTABUP: /* A B C R(A) := UpValue[B][RK(C)] */ 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; continue;
case Lua.OP_GETTABLE: /* A B C R(A):= R(B)[RK(C)] */ 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; continue;
case Lua.OP_SETTABUP: /* A B C UpValue[A][RK(B)] := RK(C) */ 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]), upValues[a].getValue().set((b = i>>>23) > 0xff? k[b & 0x0ff]: stack[b],
(c = (i>>14) & 0x1ff) > 0xff? k[c & 0x0ff]: stack[c]); (c = i>>14 & 0x1ff) > 0xff? k[c & 0x0ff]: stack[c]);
continue; continue;
case Lua.OP_SETUPVAL: /* A B UpValue[B]:= R(A) */ case Lua.OP_SETUPVAL: /* A B UpValue[B]:= R(A) */
@@ -294,47 +305,47 @@ public class LuaClosure extends LuaFunction {
continue; continue;
case Lua.OP_SETTABLE: /* A B C R(A)[RK(B)]:= RK(C) */ 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]), stack[a].set((b = i>>>23) > 0xff? k[b & 0x0ff]: stack[b],
(c = (i>>14) & 0x1ff) > 0xff? k[c & 0x0ff]: stack[c]); (c = i>>14 & 0x1ff) > 0xff? k[c & 0x0ff]: stack[c]);
continue; continue;
case Lua.OP_NEWTABLE: /* A B C R(A):= {} (size = B,C) */ 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; continue;
case Lua.OP_SELF: /* A B C R(A+1):= R(B): R(A):= R(B)[RK(C)] */ 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+1] = o = stack[i>>>23];
stack[a] = o.get((c = (i>>14) & 0x1ff) > 0xff? k[c & 0x0ff]: stack[c]); stack[a] = o.get((c = i>>14 & 0x1ff) > 0xff? k[c & 0x0ff]: stack[c]);
continue; continue;
case Lua.OP_ADD: /* A B C R(A):= RK(B) + RK(C) */ case Lua.OP_ADD: /* A B C R(A):= RK(B) + RK(C) */
stack[a] = ((b = i>>>23) > 0xff? k[b & 0x0ff]: stack[b]) 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; continue;
case Lua.OP_SUB: /* A B C R(A):= RK(B) - RK(C) */ case Lua.OP_SUB: /* A B C R(A):= RK(B) - RK(C) */
stack[a] = ((b = i>>>23) > 0xff? k[b & 0x0ff]: stack[b]) 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; continue;
case Lua.OP_MUL: /* A B C R(A):= RK(B) * RK(C) */ case Lua.OP_MUL: /* A B C R(A):= RK(B) * RK(C) */
stack[a] = ((b = i>>>23) > 0xff? k[b & 0x0ff]: stack[b]) 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; continue;
case Lua.OP_DIV: /* A B C R(A):= RK(B) / RK(C) */ case Lua.OP_DIV: /* A B C R(A):= RK(B) / RK(C) */
stack[a] = ((b = i>>>23) > 0xff? k[b & 0x0ff]: stack[b]) 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; continue;
case Lua.OP_MOD: /* A B C R(A):= RK(B) % RK(C) */ case Lua.OP_MOD: /* A B C R(A):= RK(B) % RK(C) */
stack[a] = ((b = i>>>23) > 0xff? k[b & 0x0ff]: stack[b]) 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; continue;
case Lua.OP_POW: /* A B C R(A):= RK(B) ^ RK(C) */ case Lua.OP_POW: /* A B C R(A):= RK(B) ^ RK(C) */
stack[a] = ((b = i>>>23) > 0xff? k[b & 0x0ff]: stack[b]) 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; continue;
case Lua.OP_UNM: /* A B R(A):= -R(B) */ 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) */ case Lua.OP_CONCAT: /* A B C R(A):= R(B).. ... ..R(C) */
b = i>>>23; b = i>>>23;
c = (i>>14) & 0x1ff; { c = i>>14 & 0x1ff; {
if (c > b+1) { if (c > b+1) {
Buffer sb = stack[c].buffer(); Buffer sb = stack[c].buffer();
while ( --c >= b ) 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++ */ 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]) 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; ++pc;
continue; continue;
case Lua.OP_LT: /* A B C if ((RK(B) < RK(C)) ~= A) then pc++ */ 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]) 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; ++pc;
continue; continue;
case Lua.OP_LE: /* A B C if ((RK(B) <= RK(C)) ~= A) then pc++ */ 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]) 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; ++pc;
continue; continue;
case Lua.OP_TEST: /* A C if not (R(A) <=> C) then pc++ */ 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; ++pc;
continue; continue;
case Lua.OP_TESTSET: /* A B C if (R(B) <=> C) then R(A):= R(B) else pc++ */ case Lua.OP_TESTSET: /* A B C if (R(B) <=> C) then R(A):= R(B) else pc++ */
/* note: doc appears to be reversed */ /* 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; ++pc;
else else
stack[a] = o; // TODO: should be sBx? 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)) */ 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)) { 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); v = stack[a].invoke(NONE);
top = a+v.narg(); top = a+v.narg();
continue; 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]); v = stack[a].invoke(stack[a+1]);
top = a+v.narg(); top = a+v.narg();
continue; continue;
case (1<<Lua.POS_B) | (1<<Lua.POS_C): case 1<<Lua.POS_B | 1<<Lua.POS_C:
stack[a].call(); stack[a].call();
continue; 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]); stack[a].call(stack[a+1]);
continue; 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]); stack[a].call(stack[a+1], stack[a+2]);
continue; 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]); stack[a].call(stack[a+1], stack[a+2], stack[a+3]);
continue; continue;
case (1<<Lua.POS_B) | (2<<Lua.POS_C): case 1<<Lua.POS_B | 2<<Lua.POS_C:
stack[a] = stack[a].call(); stack[a] = stack[a].call();
continue; 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]); stack[a] = stack[a].call(stack[a+1]);
continue; 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]); stack[a] = stack[a].call(stack[a+1], stack[a+2]);
continue; 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]); stack[a] = stack[a].call(stack[a+1], stack[a+2], stack[a+3]);
continue; continue;
default: default:
b = i>>>23; 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 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 varargsOf(stack, a+1, top-v.narg()-(a+1), v)); // from prev top
if (c > 0) { 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)) */ case Lua.OP_TAILCALL: /* A B C return R(A)(R(A+1), ... ,R(A+B-1)) */
switch (i & Lua.MASK_B) { switch (i & Lua.MASK_B) {
case (1<<Lua.POS_B): case 1<<Lua.POS_B:
return new TailcallVarargs(stack[a], NONE); return new TailcallVarargs(stack[a], NONE);
case (2<<Lua.POS_B): case 2<<Lua.POS_B:
return new TailcallVarargs(stack[a], stack[a+1]); 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])); 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])); return new TailcallVarargs(stack[a], varargsOf(stack[a+1], stack[a+2], stack[a+3]));
default: default:
b = i>>>23; 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)); */ 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])); v = stack[a].invoke(varargsOf(stack[a+1], stack[a+2]));
c = (i>>14) & 0x1ff; c = i>>14 & 0x1ff;
while ( --c >= 0 ) while ( --c >= 0 )
stack[a+3+c] = v.arg(c+1); stack[a+3+c] = v.arg(c+1);
v = NONE; 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 */ 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]; c = code[++pc];
int offset = (c-1)*Lua.LFIELDS_PER_FLUSH; int offset = (c-1)*Lua.LFIELDS_PER_FLUSH;
o = stack[a]; o = stack[a];
@@ -599,7 +610,7 @@ public class LuaClosure extends LuaFunction {
/** /**
* Run the error hook if there is one * Run the error hook if there is one
* *
* @param msg the message to use in error hook processing. * @param msg the message to use in error hook processing.
*/ */
String errorHook(String msg, int level) { String errorHook(String msg, int level) {
@@ -661,6 +672,7 @@ public class LuaClosure extends LuaFunction {
upValues[i].setValue(v); upValues[i].setValue(v);
} }
@Override
public String name() { public String name() {
return "<" + p.shortsource() + ":" + p.linedefined + ">"; return "<" + p.shortsource() + ":" + p.linedefined + ">";
} }

View File

@@ -10,7 +10,7 @@
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * 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> * <li>{@link #dmod_d(double, double)}</li>
* </ul> * </ul>
* <p> * <p>
* *
* @see LuaValue * @see LuaValue
* @see LuaNumber * @see LuaNumber
* @see LuaInteger * @see LuaInteger
@@ -88,106 +88,149 @@ public class LuaDouble extends LuaNumber {
this.v = d; this.v = d;
} }
@Override
public int hashCode() { public int hashCode() {
long l = Double.doubleToLongBits(v+1); long l = Double.doubleToLongBits(v+1);
return ((int) (l>>32))+(int) l; return (int) (l>>32)+(int) l;
} }
@Override
public boolean islong() { public boolean islong() {
return v == (long) v; return v == (long) v;
} }
@Override
public byte tobyte() { return (byte) (long) v; } public byte tobyte() { return (byte) (long) v; }
@Override
public char tochar() { return (char) (long) v; } public char tochar() { return (char) (long) v; }
@Override
public double todouble() { return v; } public double todouble() { return v; }
@Override
public float tofloat() { return (float) v; } public float tofloat() { return (float) v; }
@Override
public int toint() { return (int) (long) v; } public int toint() { return (int) (long) v; }
@Override
public long tolong() { return (long) v; } public long tolong() { return (long) v; }
@Override
public short toshort() { return (short) (long) v; } public short toshort() { return (short) (long) v; }
@Override
public double optdouble(double defval) { return v; } public double optdouble(double defval) { return v; }
@Override
public int optint(int defval) { return (int) (long) v; } public int optint(int defval) { return (int) (long) v; }
@Override
public LuaInteger optinteger(LuaInteger defval) { return LuaInteger.valueOf((int) (long) v); } public LuaInteger optinteger(LuaInteger defval) { return LuaInteger.valueOf((int) (long) v); }
@Override
public long optlong(long defval) { return (long) v; } public long optlong(long defval) { return (long) v; }
@Override
public LuaInteger checkinteger() { return LuaInteger.valueOf((int) (long) v); } public LuaInteger checkinteger() { return LuaInteger.valueOf((int) (long) v); }
// unary operators // unary operators
@Override
public LuaValue neg() { return valueOf(-v); } public LuaValue neg() { return valueOf(-v); }
// object equality, used for key comparison // object equality, used for key comparison
@Override
public boolean equals(Object o) { return o instanceof LuaDouble? ((LuaDouble) o).v == v: false; } public boolean equals(Object o) { return o instanceof LuaDouble? ((LuaDouble) o).v == v: false; }
// equality w/ metatable processing // equality w/ metatable processing
@Override
public LuaValue eq(LuaValue val) { return val.raweq(v)? TRUE: FALSE; } public LuaValue eq(LuaValue val) { return val.raweq(v)? TRUE: FALSE; }
@Override
public boolean eq_b(LuaValue val) { return val.raweq(v); } public boolean eq_b(LuaValue val) { return val.raweq(v); }
// equality w/o metatable processing // equality w/o metatable processing
@Override
public boolean raweq(LuaValue val) { return val.raweq(v); } public boolean raweq(LuaValue val) { return val.raweq(v); }
@Override
public boolean raweq(double val) { return v == val; } public boolean raweq(double val) { return v == val; }
@Override
public boolean raweq(int val) { return v == val; } public boolean raweq(int val) { return v == val; }
// basic binary arithmetic // basic binary arithmetic
@Override
public LuaValue add(LuaValue rhs) { return rhs.add(v); } public LuaValue add(LuaValue rhs) { return rhs.add(v); }
@Override
public LuaValue add(double lhs) { return LuaDouble.valueOf(lhs+v); } public LuaValue add(double lhs) { return LuaDouble.valueOf(lhs+v); }
@Override
public LuaValue sub(LuaValue rhs) { return rhs.subFrom(v); } public LuaValue sub(LuaValue rhs) { return rhs.subFrom(v); }
@Override
public LuaValue sub(double rhs) { return LuaDouble.valueOf(v-rhs); } public LuaValue sub(double rhs) { return LuaDouble.valueOf(v-rhs); }
@Override
public LuaValue sub(int rhs) { return LuaDouble.valueOf(v-rhs); } public LuaValue sub(int rhs) { return LuaDouble.valueOf(v-rhs); }
@Override
public LuaValue subFrom(double lhs) { return LuaDouble.valueOf(lhs-v); } public LuaValue subFrom(double lhs) { return LuaDouble.valueOf(lhs-v); }
@Override
public LuaValue mul(LuaValue rhs) { return rhs.mul(v); } public LuaValue mul(LuaValue rhs) { return rhs.mul(v); }
@Override
public LuaValue mul(double lhs) { return LuaDouble.valueOf(lhs*v); } public LuaValue mul(double lhs) { return LuaDouble.valueOf(lhs*v); }
@Override
public LuaValue mul(int lhs) { return LuaDouble.valueOf(lhs*v); } public LuaValue mul(int lhs) { return LuaDouble.valueOf(lhs*v); }
@Override
public LuaValue pow(LuaValue rhs) { return rhs.powWith(v); } public LuaValue pow(LuaValue rhs) { return rhs.powWith(v); }
@Override
public LuaValue pow(double rhs) { return MathLib.dpow(v, rhs); } public LuaValue pow(double rhs) { return MathLib.dpow(v, rhs); }
@Override
public LuaValue pow(int rhs) { return MathLib.dpow(v, rhs); } public LuaValue pow(int rhs) { return MathLib.dpow(v, rhs); }
@Override
public LuaValue powWith(double lhs) { return MathLib.dpow(lhs, v); } public LuaValue powWith(double lhs) { return MathLib.dpow(lhs, v); }
@Override
public LuaValue powWith(int lhs) { return MathLib.dpow(lhs, v); } public LuaValue powWith(int lhs) { return MathLib.dpow(lhs, v); }
@Override
public LuaValue div(LuaValue rhs) { return rhs.divInto(v); } public LuaValue div(LuaValue rhs) { return rhs.divInto(v); }
@Override
public LuaValue div(double rhs) { return LuaDouble.ddiv(v, rhs); } public LuaValue div(double rhs) { return LuaDouble.ddiv(v, rhs); }
@Override
public LuaValue div(int rhs) { return LuaDouble.ddiv(v, rhs); } public LuaValue div(int rhs) { return LuaDouble.ddiv(v, rhs); }
@Override
public LuaValue divInto(double lhs) { return LuaDouble.ddiv(lhs, v); } public LuaValue divInto(double lhs) { return LuaDouble.ddiv(lhs, v); }
@Override
public LuaValue mod(LuaValue rhs) { return rhs.modFrom(v); } public LuaValue mod(LuaValue rhs) { return rhs.modFrom(v); }
@Override
public LuaValue mod(double rhs) { return LuaDouble.dmod(v, rhs); } public LuaValue mod(double rhs) { return LuaDouble.dmod(v, rhs); }
@Override
public LuaValue mod(int rhs) { return LuaDouble.dmod(v, rhs); } public LuaValue mod(int rhs) { return LuaDouble.dmod(v, rhs); }
@Override
public LuaValue modFrom(double lhs) { return LuaDouble.dmod(lhs, v); } public LuaValue modFrom(double lhs) { return LuaDouble.dmod(lhs, v); }
/** /**
* Divide two double numbers according to lua math, and return a * Divide two double numbers according to lua math, and return a
* {@link LuaValue} result. * {@link LuaValue} result.
* *
* @param lhs Left-hand-side of the division. * @param lhs Left-hand-side of the division.
* @param rhs Right-hand-side of the division. * @param rhs Right-hand-side of the division.
* @return {@link LuaValue} for the result of the division, taking into * @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 * Divide two double numbers according to lua math, and return a double
* result. * result.
* *
* @param lhs Left-hand-side of the division. * @param lhs Left-hand-side of the division.
* @param rhs Right-hand-side of the division. * @param rhs Right-hand-side of the division.
* @return Value of the division, taking into account positive and negative * @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 * Take modulo double numbers according to lua math, and return a
* {@link LuaValue} result. * {@link LuaValue} result.
* *
* @param lhs Left-hand-side of the modulo. * @param lhs Left-hand-side of the modulo.
* @param rhs Right-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 * @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 * Take modulo for double numbers according to lua math, and return a double
* result. * result.
* *
* @param lhs Left-hand-side of the modulo. * @param lhs Left-hand-side of the modulo.
* @param rhs Right-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 * @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 // 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; } public LuaValue lt(double rhs) { return v < rhs? TRUE: FALSE; }
@Override
public LuaValue lt(int rhs) { return v < rhs? TRUE: FALSE; } 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); } 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; } public boolean lt_b(int rhs) { return v < rhs; }
@Override
public boolean lt_b(double rhs) { return v < rhs; } public boolean lt_b(double rhs) { return v < rhs; }
@Override
public LuaValue lteq(LuaValue rhs) { 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; } public LuaValue lteq(double rhs) { return v <= rhs? TRUE: FALSE; }
@Override
public LuaValue lteq(int rhs) { return v <= rhs? TRUE: FALSE; } 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); } 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; } public boolean lteq_b(int rhs) { return v <= rhs; }
@Override
public boolean lteq_b(double rhs) { return v <= rhs; } 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; } public LuaValue gt(double rhs) { return v > rhs? TRUE: FALSE; }
@Override
public LuaValue gt(int rhs) { return v > rhs? TRUE: FALSE; } 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); } 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; } public boolean gt_b(int rhs) { return v > rhs; }
@Override
public boolean gt_b(double rhs) { return v > rhs; } public boolean gt_b(double rhs) { return v > rhs; }
@Override
public LuaValue gteq(LuaValue rhs) { 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; } public LuaValue gteq(double rhs) { return v >= rhs? TRUE: FALSE; }
@Override
public LuaValue gteq(int rhs) { return v >= rhs? TRUE: FALSE; } 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); } 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; } public boolean gteq_b(int rhs) { return v >= rhs; }
@Override
public boolean gteq_b(double rhs) { return v >= rhs; } public boolean gteq_b(double rhs) { return v >= rhs; }
// string comparison // string comparison
@Override
public int strcmp(LuaString rhs) { typerror("attempt to compare number with string"); return 0; } public int strcmp(LuaString rhs) { typerror("attempt to compare number with string"); return 0; }
@Override
public String tojstring() { public String tojstring() {
/* /*
if ( v == 0.0 ) { // never occurs in J2me if ( v == 0.0 ) { // never occurs in J2me
@@ -325,58 +394,73 @@ public class LuaDouble extends LuaNumber {
if (Double.isNaN(v)) if (Double.isNaN(v))
return JSTR_NAN; return JSTR_NAN;
if (Double.isInfinite(v)) if (Double.isInfinite(v))
return (v < 0? JSTR_NEGINF: JSTR_POSINF); return v < 0? JSTR_NEGINF: JSTR_POSINF;
return Float.toString((float) v); return Float.toString((float) v);
} }
@Override
public LuaString strvalue() { public LuaString strvalue() {
return LuaString.valueOf(tojstring()); return LuaString.valueOf(tojstring());
} }
@Override
public LuaString optstring(LuaString defval) { public LuaString optstring(LuaString defval) {
return LuaString.valueOf(tojstring()); return LuaString.valueOf(tojstring());
} }
@Override
public LuaValue tostring() { public LuaValue tostring() {
return LuaString.valueOf(tojstring()); return LuaString.valueOf(tojstring());
} }
@Override
public String optjstring(String defval) { public String optjstring(String defval) {
return tojstring(); return tojstring();
} }
@Override
public LuaNumber optnumber(LuaNumber defval) { public LuaNumber optnumber(LuaNumber defval) {
return this; return this;
} }
@Override
public boolean isnumber() { public boolean isnumber() {
return true; return true;
} }
@Override
public boolean isstring() { public boolean isstring() {
return true; return true;
} }
@Override
public LuaValue tonumber() { public LuaValue tonumber() {
return this; return this;
} }
@Override
public int checkint() { return (int) (long) v; } public int checkint() { return (int) (long) v; }
@Override
public long checklong() { return (long) v; } public long checklong() { return (long) v; }
@Override
public LuaNumber checknumber() { return this; } public LuaNumber checknumber() { return this; }
@Override
public double checkdouble() { return v; } public double checkdouble() { return v; }
@Override
public String checkjstring() { public String checkjstring() {
return tojstring(); return tojstring();
} }
@Override
public LuaString checkstring() { public LuaString checkstring() {
return LuaString.valueOf(tojstring()); return LuaString.valueOf(tojstring());
} }
@Override
public boolean isvalidkey() { public boolean isvalidkey() {
return !Double.isNaN(v); return !Double.isNaN(v);
} }

View File

@@ -10,7 +10,7 @@
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * 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 * Get the string message if it was supplied, or a string representation of
* the message object if that was supplied. * the message object if that was supplied.
*/ */
@Override
public String getMessage() { public String getMessage() {
if (traceback != null) if (traceback != null)
return traceback; return traceback;
@@ -68,7 +69,7 @@ public class LuaError extends RuntimeException {
/** /**
* Get the LuaValue that was provided in the constructor, or a LuaString * Get the LuaValue that was provided in the constructor, or a LuaString
* containing the message if it was a string error argument. * containing the message if it was a string error argument.
* *
* @return LuaValue which was used in the constructor, or a LuaString * @return LuaValue which was used in the constructor, or a LuaString
* containing the message. * containing the message.
*/ */
@@ -83,7 +84,7 @@ public class LuaError extends RuntimeException {
* Construct LuaError when a program exception occurs. * Construct LuaError when a program exception occurs.
* <p> * <p>
* All errors generated from lua code should throw LuaError(String) instead. * All errors generated from lua code should throw LuaError(String) instead.
* *
* @param cause the Throwable that caused the error, if known. * @param cause the Throwable that caused the error, if known.
*/ */
public LuaError(Throwable cause) { public LuaError(Throwable cause) {
@@ -94,7 +95,7 @@ public class LuaError extends RuntimeException {
/** /**
* Construct a LuaError with a specific message. * Construct a LuaError with a specific message.
* *
* @param message message to supply * @param message message to supply
*/ */
public LuaError(String message) { 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 * Construct a LuaError with a message, and level to draw line number
* information from. * information from.
* *
* @param message message to supply * @param message message to supply
* @param level where to supply line info from in call stack * @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 * Construct a LuaError with a LuaValue as the message object, and level to
* draw line number information from. * draw line number information from.
* *
* @param message_object message string or object to supply * @param message_object message string or object to supply
*/ */
public LuaError(LuaValue message_object) { public LuaError(LuaValue message_object) {
@@ -129,6 +130,7 @@ public class LuaError extends RuntimeException {
/** /**
* Get the cause, if any. * Get the cause, if any.
*/ */
@Override
public Throwable getCause() { return cause; } public Throwable getCause() { return cause; }
} }

View File

@@ -10,7 +10,7 @@
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * 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 * base class for all built-in library functions coded in Java, and
* {@link LuaClosure}, which represents a lua closure whose bytecode is * {@link LuaClosure}, which represents a lua closure whose bytecode is
* interpreted when the function is invoked. * interpreted when the function is invoked.
* *
* @see LuaValue * @see LuaValue
* @see LuaClosure * @see LuaClosure
* @see org.luaj.vm2.lib.LibFunction * @see org.luaj.vm2.lib.LibFunction
@@ -38,34 +38,42 @@ abstract public class LuaFunction extends LuaValue {
/** Shared static metatable for all functions and closures. */ /** Shared static metatable for all functions and closures. */
public static LuaValue s_metatable; public static LuaValue s_metatable;
@Override
public int type() { public int type() {
return TFUNCTION; return TFUNCTION;
} }
@Override
public String typename() { public String typename() {
return "function"; return "function";
} }
@Override
public boolean isfunction() { public boolean isfunction() {
return true; return true;
} }
@Override
public LuaFunction checkfunction() { public LuaFunction checkfunction() {
return this; return this;
} }
@Override
public LuaFunction optfunction(LuaFunction defval) { public LuaFunction optfunction(LuaFunction defval) {
return this; return this;
} }
@Override
public LuaValue getmetatable() { public LuaValue getmetatable() {
return s_metatable; return s_metatable;
} }
@Override
public String tojstring() { public String tojstring() {
return "function: " + classnamestub(); return "function: " + classnamestub();
} }
@Override
public LuaString strvalue() { public LuaString strvalue() {
return valueOf(tojstring()); 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 * Return the last part of the class name, to be used as a function name in
* tojstring and elsewhere. * tojstring and elsewhere.
* *
* @return String naming the last part of the class name after the last dot * @return String naming the last part of the class name after the last dot
* (.) or dollar sign ($). If the first character is '_', it is * (.) or dollar sign ($). If the first character is '_', it is
* skipped. * skipped.
@@ -90,7 +98,7 @@ abstract public class LuaFunction extends LuaValue {
* Return a human-readable name for this function. Returns the last part of * 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 * the class name by default. Is overridden by LuaClosure to return the
* source file and line, and by LibFunctions to return the name. * source file and line, and by LibFunctions to return the name.
* *
* @return common name for this function. * @return common name for this function.
*/ */
public String name() { public String name() {

View File

@@ -10,7 +10,7 @@
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -33,7 +33,7 @@ import org.luaj.vm2.lib.MathLib;
* <p> * <p>
* There are no API's specific to LuaInteger that are useful beyond what is * There are no API's specific to LuaInteger that are useful beyond what is
* already exposed in {@link LuaValue}. * already exposed in {@link LuaValue}.
* *
* @see LuaValue * @see LuaValue
* @see LuaNumber * @see LuaNumber
* @see LuaDouble * @see LuaDouble
@@ -50,12 +50,12 @@ public class LuaInteger extends LuaNumber {
public static LuaInteger valueOf(int i) { public static LuaInteger valueOf(int i) {
return i <= 255 && i >= -256? intValues[i+256]: new LuaInteger(i); return i <= 255 && i >= -256? intValues[i+256]: new LuaInteger(i);
}; }
// TODO consider moving this to LuaValue // TODO consider moving this to LuaValue
/** /**
* Return a LuaNumber that represents the value provided * Return a LuaNumber that represents the value provided
* *
* @param l long value to represent. * @param l long value to represent.
* @return LuaNumber that is eithe LuaInteger or LuaDouble representing l * @return LuaNumber that is eithe LuaInteger or LuaDouble representing l
* @see LuaValue#valueOf(int) * @see LuaValue#valueOf(int)
@@ -63,7 +63,7 @@ public class LuaInteger extends LuaNumber {
*/ */
public static LuaNumber valueOf(long l) { public static LuaNumber valueOf(long l) {
int i = (int) 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); : (LuaNumber) LuaDouble.valueOf(l);
} }
@@ -72,69 +72,91 @@ public class LuaInteger extends LuaNumber {
/** /**
* Package protected constructor. * Package protected constructor.
* *
* @see LuaValue#valueOf(int) * @see LuaValue#valueOf(int)
**/ **/
LuaInteger(int i) { LuaInteger(int i) {
this.v = i; this.v = i;
} }
@Override
public boolean isint() { return true; } public boolean isint() { return true; }
@Override
public boolean isinttype() { return true; } public boolean isinttype() { return true; }
@Override
public boolean islong() { return true; } public boolean islong() { return true; }
@Override
public byte tobyte() { return (byte) v; } public byte tobyte() { return (byte) v; }
@Override
public char tochar() { return (char) v; } public char tochar() { return (char) v; }
@Override
public double todouble() { return v; } public double todouble() { return v; }
@Override
public float tofloat() { return v; } public float tofloat() { return v; }
@Override
public int toint() { return v; } public int toint() { return v; }
@Override
public long tolong() { return v; } public long tolong() { return v; }
@Override
public short toshort() { return (short) v; } public short toshort() { return (short) v; }
@Override
public double optdouble(double defval) { return v; } public double optdouble(double defval) { return v; }
@Override
public int optint(int defval) { return v; } public int optint(int defval) { return v; }
@Override
public LuaInteger optinteger(LuaInteger defval) { return this; } public LuaInteger optinteger(LuaInteger defval) { return this; }
@Override
public long optlong(long defval) { return v; } public long optlong(long defval) { return v; }
@Override
public String tojstring() { public String tojstring() {
return Integer.toString(v); return Integer.toString(v);
} }
@Override
public LuaString strvalue() { public LuaString strvalue() {
return LuaString.valueOf(Integer.toString(v)); return LuaString.valueOf(Integer.toString(v));
} }
@Override
public LuaString optstring(LuaString defval) { public LuaString optstring(LuaString defval) {
return LuaString.valueOf(Integer.toString(v)); return LuaString.valueOf(Integer.toString(v));
} }
@Override
public LuaValue tostring() { public LuaValue tostring() {
return LuaString.valueOf(Integer.toString(v)); return LuaString.valueOf(Integer.toString(v));
} }
@Override
public String optjstring(String defval) { public String optjstring(String defval) {
return Integer.toString(v); return Integer.toString(v);
} }
@Override
public LuaInteger checkinteger() { public LuaInteger checkinteger() {
return this; return this;
} }
@Override
public boolean isstring() { public boolean isstring() {
return true; return true;
} }
@Override
public int hashCode() { public int hashCode() {
return v; return v;
} }
@@ -144,144 +166,205 @@ public class LuaInteger extends LuaNumber {
} }
// unary operators // unary operators
@Override
public LuaValue neg() { return valueOf(-(long) v); } public LuaValue neg() { return valueOf(-(long) v); }
// object equality, used for key comparison // object equality, used for key comparison
@Override
public boolean equals(Object o) { return o instanceof LuaInteger? ((LuaInteger) o).v == v: false; } public boolean equals(Object o) { return o instanceof LuaInteger? ((LuaInteger) o).v == v: false; }
// equality w/ metatable processing // equality w/ metatable processing
@Override
public LuaValue eq(LuaValue val) { return val.raweq(v)? TRUE: FALSE; } public LuaValue eq(LuaValue val) { return val.raweq(v)? TRUE: FALSE; }
@Override
public boolean eq_b(LuaValue val) { return val.raweq(v); } public boolean eq_b(LuaValue val) { return val.raweq(v); }
// equality w/o metatable processing // equality w/o metatable processing
@Override
public boolean raweq(LuaValue val) { return val.raweq(v); } public boolean raweq(LuaValue val) { return val.raweq(v); }
@Override
public boolean raweq(double val) { return v == val; } public boolean raweq(double val) { return v == val; }
@Override
public boolean raweq(int val) { return v == val; } public boolean raweq(int val) { return v == val; }
// arithmetic operators // arithmetic operators
@Override
public LuaValue add(LuaValue rhs) { return rhs.add(v); } public LuaValue add(LuaValue rhs) { return rhs.add(v); }
@Override
public LuaValue add(double lhs) { return LuaDouble.valueOf(lhs+v); } public LuaValue add(double lhs) { return LuaDouble.valueOf(lhs+v); }
@Override
public LuaValue add(int lhs) { return LuaInteger.valueOf(lhs+(long) v); } public LuaValue add(int lhs) { return LuaInteger.valueOf(lhs+(long) v); }
@Override
public LuaValue sub(LuaValue rhs) { return rhs.subFrom(v); } public LuaValue sub(LuaValue rhs) { return rhs.subFrom(v); }
@Override
public LuaValue sub(double rhs) { return LuaDouble.valueOf(v-rhs); } 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); } public LuaValue subFrom(double lhs) { return LuaDouble.valueOf(lhs-v); }
@Override
public LuaValue subFrom(int lhs) { return LuaInteger.valueOf(lhs-(long) v); } public LuaValue subFrom(int lhs) { return LuaInteger.valueOf(lhs-(long) v); }
@Override
public LuaValue mul(LuaValue rhs) { return rhs.mul(v); } public LuaValue mul(LuaValue rhs) { return rhs.mul(v); }
@Override
public LuaValue mul(double lhs) { return LuaDouble.valueOf(lhs*v); } public LuaValue mul(double lhs) { return LuaDouble.valueOf(lhs*v); }
@Override
public LuaValue mul(int lhs) { return LuaInteger.valueOf(lhs*(long) v); } public LuaValue mul(int lhs) { return LuaInteger.valueOf(lhs*(long) v); }
@Override
public LuaValue pow(LuaValue rhs) { return rhs.powWith(v); } public LuaValue pow(LuaValue rhs) { return rhs.powWith(v); }
@Override
public LuaValue pow(double rhs) { return MathLib.dpow(v, rhs); } public LuaValue pow(double rhs) { return MathLib.dpow(v, rhs); }
@Override
public LuaValue pow(int rhs) { return MathLib.dpow(v, rhs); } public LuaValue pow(int rhs) { return MathLib.dpow(v, rhs); }
@Override
public LuaValue powWith(double lhs) { return MathLib.dpow(lhs, v); } public LuaValue powWith(double lhs) { return MathLib.dpow(lhs, v); }
@Override
public LuaValue powWith(int lhs) { return MathLib.dpow(lhs, v); } public LuaValue powWith(int lhs) { return MathLib.dpow(lhs, v); }
@Override
public LuaValue div(LuaValue rhs) { return rhs.divInto(v); } public LuaValue div(LuaValue rhs) { return rhs.divInto(v); }
@Override
public LuaValue div(double rhs) { return LuaDouble.ddiv(v, rhs); } public LuaValue div(double rhs) { return LuaDouble.ddiv(v, rhs); }
@Override
public LuaValue div(int rhs) { return LuaDouble.ddiv(v, rhs); } public LuaValue div(int rhs) { return LuaDouble.ddiv(v, rhs); }
@Override
public LuaValue divInto(double lhs) { return LuaDouble.ddiv(lhs, v); } public LuaValue divInto(double lhs) { return LuaDouble.ddiv(lhs, v); }
@Override
public LuaValue mod(LuaValue rhs) { return rhs.modFrom(v); } public LuaValue mod(LuaValue rhs) { return rhs.modFrom(v); }
@Override
public LuaValue mod(double rhs) { return LuaDouble.dmod(v, rhs); } public LuaValue mod(double rhs) { return LuaDouble.dmod(v, rhs); }
@Override
public LuaValue mod(int rhs) { return LuaDouble.dmod(v, rhs); } public LuaValue mod(int rhs) { return LuaDouble.dmod(v, rhs); }
@Override
public LuaValue modFrom(double lhs) { return LuaDouble.dmod(lhs, v); } public LuaValue modFrom(double lhs) { return LuaDouble.dmod(lhs, v); }
// relational operators // 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; } public LuaValue lt(double rhs) { return v < rhs? TRUE: FALSE; }
@Override
public LuaValue lt(int rhs) { return v < rhs? TRUE: FALSE; } 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); } 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; } public boolean lt_b(int rhs) { return v < rhs; }
@Override
public boolean lt_b(double rhs) { return v < rhs; } public boolean lt_b(double rhs) { return v < rhs; }
@Override
public LuaValue lteq(LuaValue rhs) { 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; } public LuaValue lteq(double rhs) { return v <= rhs? TRUE: FALSE; }
@Override
public LuaValue lteq(int rhs) { return v <= rhs? TRUE: FALSE; } 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); } 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; } public boolean lteq_b(int rhs) { return v <= rhs; }
@Override
public boolean lteq_b(double rhs) { return v <= rhs; } 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; } public LuaValue gt(double rhs) { return v > rhs? TRUE: FALSE; }
@Override
public LuaValue gt(int rhs) { return v > rhs? TRUE: FALSE; } 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); } 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; } public boolean gt_b(int rhs) { return v > rhs; }
@Override
public boolean gt_b(double rhs) { return v > rhs; } public boolean gt_b(double rhs) { return v > rhs; }
@Override
public LuaValue gteq(LuaValue rhs) { 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; } public LuaValue gteq(double rhs) { return v >= rhs? TRUE: FALSE; }
@Override
public LuaValue gteq(int rhs) { return v >= rhs? TRUE: FALSE; } 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); } 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; } public boolean gteq_b(int rhs) { return v >= rhs; }
@Override
public boolean gteq_b(double rhs) { return v >= rhs; } public boolean gteq_b(double rhs) { return v >= rhs; }
// string comparison // string comparison
@Override
public int strcmp(LuaString rhs) { typerror("attempt to compare number with string"); return 0; } public int strcmp(LuaString rhs) { typerror("attempt to compare number with string"); return 0; }
@Override
public int checkint() { public int checkint() {
return v; return v;
} }
@Override
public long checklong() { public long checklong() {
return v; return v;
} }
@Override
public double checkdouble() { public double checkdouble() {
return v; return v;
} }
@Override
public String checkjstring() { public String checkjstring() {
return String.valueOf(v); return String.valueOf(v);
} }
@Override
public LuaString checkstring() { public LuaString checkstring() {
return valueOf(String.valueOf(v)); return valueOf(String.valueOf(v));
} }

View File

@@ -10,7 +10,7 @@
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * 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. * recommended approach is to use the method {@link LuaValue#isnil()} instead.
* By using that any ambiguities between {@link LuaValue#NIL} and * By using that any ambiguities between {@link LuaValue#NIL} and
* {@link LuaValue#NONE} are avoided. * {@link LuaValue#NONE} are avoided.
* *
* @see LuaValue * @see LuaValue
* @see LuaValue#NIL * @see LuaValue#NIL
*/ */
@@ -45,78 +45,104 @@ public class LuaNil extends LuaValue {
LuaNil() {} LuaNil() {}
@Override
public int type() { public int type() {
return LuaValue.TNIL; return LuaValue.TNIL;
} }
@Override
public String toString() { public String toString() {
return "nil"; return "nil";
} }
@Override
public String typename() { public String typename() {
return "nil"; return "nil";
} }
@Override
public String tojstring() { public String tojstring() {
return "nil"; return "nil";
} }
@Override
public LuaValue not() { public LuaValue not() {
return LuaValue.TRUE; return LuaValue.TRUE;
} }
@Override
public boolean toboolean() { public boolean toboolean() {
return false; return false;
} }
@Override
public boolean isnil() { public boolean isnil() {
return true; return true;
} }
@Override
public LuaValue getmetatable() { public LuaValue getmetatable() {
return s_metatable; return s_metatable;
} }
@Override
public boolean equals(Object o) { public boolean equals(Object o) {
return o instanceof LuaNil; return o instanceof LuaNil;
} }
@Override
public LuaValue checknotnil() { public LuaValue checknotnil() {
return argerror("value"); return argerror("value");
} }
@Override
public boolean isvalidkey() { public boolean isvalidkey() {
return false; return false;
} }
// optional argument conversions - nil alwas falls badk to default value // optional argument conversions - nil alwas falls badk to default value
@Override
public boolean optboolean(boolean defval) { return defval; } public boolean optboolean(boolean defval) { return defval; }
@Override
public LuaClosure optclosure(LuaClosure defval) { return defval; } public LuaClosure optclosure(LuaClosure defval) { return defval; }
@Override
public double optdouble(double defval) { return defval; } public double optdouble(double defval) { return defval; }
@Override
public LuaFunction optfunction(LuaFunction defval) { return defval; } public LuaFunction optfunction(LuaFunction defval) { return defval; }
@Override
public int optint(int defval) { return defval; } public int optint(int defval) { return defval; }
@Override
public LuaInteger optinteger(LuaInteger defval) { return defval; } public LuaInteger optinteger(LuaInteger defval) { return defval; }
@Override
public long optlong(long defval) { return defval; } public long optlong(long defval) { return defval; }
@Override
public LuaNumber optnumber(LuaNumber defval) { return defval; } public LuaNumber optnumber(LuaNumber defval) { return defval; }
@Override
public LuaTable opttable(LuaTable defval) { return defval; } public LuaTable opttable(LuaTable defval) { return defval; }
@Override
public LuaThread optthread(LuaThread defval) { return defval; } public LuaThread optthread(LuaThread defval) { return defval; }
@Override
public String optjstring(String defval) { return defval; } public String optjstring(String defval) { return defval; }
@Override
public LuaString optstring(LuaString defval) { return defval; } public LuaString optstring(LuaString defval) { return defval; }
@Override
public Object optuserdata(Object defval) { return defval; } public Object optuserdata(Object defval) { return defval; }
@Override
public Object optuserdata(Class c, Object defval) { return defval; } public Object optuserdata(Class c, Object defval) { return defval; }
@Override
public LuaValue optvalue(LuaValue defval) { return defval; } 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 * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -26,59 +26,72 @@ package org.luaj.vm2;
* <p> * <p>
* The main subclasses are {@link LuaInteger} which holds values that fit in a * The main subclasses are {@link LuaInteger} which holds values that fit in a
* java int, and {@link LuaDouble} which holds all other number values. * java int, and {@link LuaDouble} which holds all other number values.
* *
* @see LuaInteger * @see LuaInteger
* @see LuaDouble * @see LuaDouble
* @see LuaValue * @see LuaValue
* *
*/ */
abstract public class LuaNumber extends LuaValue { abstract public class LuaNumber extends LuaValue {
/** Shared static metatable for all number values represented in lua. */ /** Shared static metatable for all number values represented in lua. */
public static LuaValue s_metatable; public static LuaValue s_metatable;
@Override
public int type() { public int type() {
return TNUMBER; return TNUMBER;
} }
@Override
public String typename() { public String typename() {
return "number"; return "number";
} }
@Override
public LuaNumber checknumber() { public LuaNumber checknumber() {
return this; return this;
} }
@Override
public LuaNumber checknumber(String errmsg) { public LuaNumber checknumber(String errmsg) {
return this; return this;
} }
@Override
public LuaNumber optnumber(LuaNumber defval) { public LuaNumber optnumber(LuaNumber defval) {
return this; return this;
} }
@Override
public LuaValue tonumber() { public LuaValue tonumber() {
return this; return this;
} }
@Override
public boolean isnumber() { public boolean isnumber() {
return true; return true;
} }
@Override
public boolean isstring() { public boolean isstring() {
return true; return true;
} }
@Override
public LuaValue getmetatable() { public LuaValue getmetatable() {
return s_metatable; return s_metatable;
} }
@Override
public LuaValue concat(LuaValue rhs) { return rhs.concatTo(this); } public LuaValue concat(LuaValue rhs) { return rhs.concatTo(this); }
@Override
public Buffer concat(Buffer rhs) { return rhs.concatTo(this); } public Buffer concat(Buffer rhs) { return rhs.concatTo(this); }
@Override
public LuaValue concatTo(LuaNumber lhs) { return strvalue().concatTo(lhs.strvalue()); } public LuaValue concatTo(LuaNumber lhs) { return strvalue().concatTo(lhs.strvalue()); }
@Override
public LuaValue concatTo(LuaString lhs) { return strvalue().concatTo(lhs); } 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 * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * 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 #encodeToUtf8(char[], int, byte[], int)}, and
* {@link #decodeAsUtf8(byte[], int, int)} are used to convert back and forth * {@link #decodeAsUtf8(byte[], int, int)} are used to convert back and forth
* between UTF8 byte arrays and character arrays. * between UTF8 byte arrays and character arrays.
* *
* @see LuaValue * @see LuaValue
* @see LuaValue#valueOf(String) * @see LuaValue#valueOf(String)
* @see LuaValue#valueOf(byte[]) * @see LuaValue#valueOf(byte[])
@@ -116,7 +116,7 @@ public class LuaString extends LuaValue {
/** /**
* Get a {@link LuaString} instance whose bytes match the supplied Java * Get a {@link LuaString} instance whose bytes match the supplied Java
* String using the UTF8 encoding. * String using the UTF8 encoding.
* *
* @param string Java String containing characters to encode as UTF8 * @param string Java String containing characters to encode as UTF8
* @return {@link LuaString} with UTF8 bytes corresponding to the supplied * @return {@link LuaString} with UTF8 bytes corresponding to the supplied
* String * String
@@ -137,7 +137,7 @@ public class LuaString extends LuaValue {
* the backing, otherwise the bytes will be copied to a new byte array, and * the backing, otherwise the bytes will be copied to a new byte array, and
* cache lookup may be performed. * cache lookup may be performed.
* <p> * <p>
* *
* @param bytes byte buffer * @param bytes byte buffer
* @param off offset into the byte buffer * @param off offset into the byte buffer
* @param len length of 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) if (len > RECENT_STRINGS_MAX_LENGTH)
return valueFromCopy(bytes, off, len); return valueFromCopy(bytes, off, len);
final int hash = hashCode(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]; final LuaString t = RecentShortStrings.recent_short_strings[bucket];
if (t != null && t.m_hashcode == hash && t.byteseq(bytes, off, len)) if (t != null && t.m_hashcode == hash && t.byteseq(bytes, off, len))
return t; return t;
@@ -171,7 +171,7 @@ public class LuaString extends LuaValue {
* However, if the string is short enough the short-string cache is checked * 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. * for a match which may be used instead of the supplied byte array.
* <p> * <p>
* *
* @param bytes byte buffer * @param bytes byte buffer
* @return {@link LuaString} wrapping the byte buffer, or an equivalent * @return {@link LuaString} wrapping the byte buffer, or an equivalent
* string. * string.
@@ -180,7 +180,7 @@ public class LuaString extends LuaValue {
if (bytes.length > RECENT_STRINGS_MAX_LENGTH) if (bytes.length > RECENT_STRINGS_MAX_LENGTH)
return new LuaString(bytes, off, len); return new LuaString(bytes, off, len);
final int hash = hashCode(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]; final LuaString t = RecentShortStrings.recent_short_strings[bucket];
if (t != null && t.m_hashcode == hash && t.byteseq(bytes, off, len)) if (t != null && t.m_hashcode == hash && t.byteseq(bytes, off, len))
return t; return t;
@@ -198,7 +198,7 @@ public class LuaString extends LuaValue {
* <p> * <p>
* This is most useful for constructing byte sequences that do not conform * This is most useful for constructing byte sequences that do not conform
* to UTF8. * to UTF8.
* *
* @param bytes array of char, whose values are truncated at 8-bits each and * @param bytes array of char, whose values are truncated at 8-bits each and
* put into a byte array. * put into a byte array.
* @return {@link LuaString} wrapping a copy of the byte buffer * @return {@link LuaString} wrapping a copy of the byte buffer
@@ -216,7 +216,7 @@ public class LuaString extends LuaValue {
* <p> * <p>
* This is most useful for constructing byte sequences that do not conform * This is most useful for constructing byte sequences that do not conform
* to UTF8. * to UTF8.
* *
* @param bytes array of char, whose values are truncated at 8-bits each and * @param bytes array of char, whose values are truncated at 8-bits each and
* put into a byte array. * put into a byte array.
* @return {@link LuaString} wrapping a copy of the byte buffer * @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 * of the bytes array, or be an existing LuaString used already having the
* same value. * same value.
* <p> * <p>
* *
* @param bytes byte buffer * @param bytes byte buffer
* @return {@link LuaString} wrapping the byte buffer * @return {@link LuaString} wrapping the byte buffer
*/ */
@@ -252,7 +252,7 @@ public class LuaString extends LuaValue {
* <p> * <p>
* The caller must not mutate the contents of the byte array after this * 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. * call, as it may be used elsewhere due to recent short string caching.
* *
* @param bytes byte buffer * @param bytes byte buffer
* @return {@link LuaString} wrapping the 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 * The array is used directly after this is called, so clients must not
* change contents. * change contents.
* <p> * <p>
* *
* @param bytes byte buffer * @param bytes byte buffer
* @param offset offset into the byte buffer * @param offset offset into the byte buffer
* @param length length of 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); this.m_hashcode = hashCode(bytes, offset, length);
} }
@Override
public boolean isstring() { public boolean isstring() {
return true; return true;
} }
@Override
public LuaValue getmetatable() { public LuaValue getmetatable() {
return s_metatable; return s_metatable;
} }
@Override
public int type() { public int type() {
return LuaValue.TSTRING; return LuaValue.TSTRING;
} }
@Override
public String typename() { public String typename() {
return "string"; return "string";
} }
@Override
public String tojstring() { public String tojstring() {
return decodeAsUtf8(m_bytes, m_offset, m_length); return decodeAsUtf8(m_bytes, m_offset, m_length);
} }
// unary operators // unary operators
@Override
public LuaValue neg() { double d = scannumber(); return Double.isNaN(d)? super.neg(): valueOf(-d); } public LuaValue neg() { double d = scannumber(); return Double.isNaN(d)? super.neg(): valueOf(-d); }
// basic binary arithmetic // basic binary arithmetic
@Override
public LuaValue add(LuaValue rhs) { public LuaValue add(LuaValue rhs) {
double d = scannumber(); double d = scannumber();
return Double.isNaN(d)? arithmt(ADD, rhs): rhs.add(d); return Double.isNaN(d)? arithmt(ADD, rhs): rhs.add(d);
} }
@Override
public LuaValue add(double rhs) { return valueOf(checkarith()+rhs); } public LuaValue add(double rhs) { return valueOf(checkarith()+rhs); }
@Override
public LuaValue add(int rhs) { return valueOf(checkarith()+rhs); } public LuaValue add(int rhs) { return valueOf(checkarith()+rhs); }
@Override
public LuaValue sub(LuaValue rhs) { public LuaValue sub(LuaValue rhs) {
double d = scannumber(); double d = scannumber();
return Double.isNaN(d)? arithmt(SUB, rhs): rhs.subFrom(d); return Double.isNaN(d)? arithmt(SUB, rhs): rhs.subFrom(d);
} }
@Override
public LuaValue sub(double rhs) { return valueOf(checkarith()-rhs); } public LuaValue sub(double rhs) { return valueOf(checkarith()-rhs); }
@Override
public LuaValue sub(int rhs) { return valueOf(checkarith()-rhs); } public LuaValue sub(int rhs) { return valueOf(checkarith()-rhs); }
@Override
public LuaValue subFrom(double lhs) { return valueOf(lhs-checkarith()); } public LuaValue subFrom(double lhs) { return valueOf(lhs-checkarith()); }
@Override
public LuaValue mul(LuaValue rhs) { public LuaValue mul(LuaValue rhs) {
double d = scannumber(); double d = scannumber();
return Double.isNaN(d)? arithmt(MUL, rhs): rhs.mul(d); return Double.isNaN(d)? arithmt(MUL, rhs): rhs.mul(d);
} }
@Override
public LuaValue mul(double rhs) { return valueOf(checkarith()*rhs); } public LuaValue mul(double rhs) { return valueOf(checkarith()*rhs); }
@Override
public LuaValue mul(int rhs) { return valueOf(checkarith()*rhs); } public LuaValue mul(int rhs) { return valueOf(checkarith()*rhs); }
@Override
public LuaValue pow(LuaValue rhs) { public LuaValue pow(LuaValue rhs) {
double d = scannumber(); double d = scannumber();
return Double.isNaN(d)? arithmt(POW, rhs): rhs.powWith(d); return Double.isNaN(d)? arithmt(POW, rhs): rhs.powWith(d);
} }
@Override
public LuaValue pow(double rhs) { return MathLib.dpow(checkarith(), rhs); } public LuaValue pow(double rhs) { return MathLib.dpow(checkarith(), rhs); }
@Override
public LuaValue pow(int rhs) { return MathLib.dpow(checkarith(), rhs); } public LuaValue pow(int rhs) { return MathLib.dpow(checkarith(), rhs); }
@Override
public LuaValue powWith(double lhs) { return MathLib.dpow(lhs, checkarith()); } public LuaValue powWith(double lhs) { return MathLib.dpow(lhs, checkarith()); }
@Override
public LuaValue powWith(int lhs) { return MathLib.dpow(lhs, checkarith()); } public LuaValue powWith(int lhs) { return MathLib.dpow(lhs, checkarith()); }
@Override
public LuaValue div(LuaValue rhs) { public LuaValue div(LuaValue rhs) {
double d = scannumber(); double d = scannumber();
return Double.isNaN(d)? arithmt(DIV, rhs): rhs.divInto(d); return Double.isNaN(d)? arithmt(DIV, rhs): rhs.divInto(d);
} }
@Override
public LuaValue div(double rhs) { return LuaDouble.ddiv(checkarith(), rhs); } public LuaValue div(double rhs) { return LuaDouble.ddiv(checkarith(), rhs); }
@Override
public LuaValue div(int rhs) { return LuaDouble.ddiv(checkarith(), rhs); } public LuaValue div(int rhs) { return LuaDouble.ddiv(checkarith(), rhs); }
@Override
public LuaValue divInto(double lhs) { return LuaDouble.ddiv(lhs, checkarith()); } public LuaValue divInto(double lhs) { return LuaDouble.ddiv(lhs, checkarith()); }
@Override
public LuaValue mod(LuaValue rhs) { public LuaValue mod(LuaValue rhs) {
double d = scannumber(); double d = scannumber();
return Double.isNaN(d)? arithmt(MOD, rhs): rhs.modFrom(d); return Double.isNaN(d)? arithmt(MOD, rhs): rhs.modFrom(d);
} }
@Override
public LuaValue mod(double rhs) { return LuaDouble.dmod(checkarith(), rhs); } public LuaValue mod(double rhs) { return LuaDouble.dmod(checkarith(), rhs); }
@Override
public LuaValue mod(int rhs) { return LuaDouble.dmod(checkarith(), rhs); } public LuaValue mod(int rhs) { return LuaDouble.dmod(checkarith(), rhs); }
@Override
public LuaValue modFrom(double lhs) { return LuaDouble.dmod(lhs, checkarith()); } public LuaValue modFrom(double lhs) { return LuaDouble.dmod(lhs, checkarith()); }
// relational operators, these only work with other strings // relational operators, these only work with other strings
@Override
public LuaValue lt(LuaValue rhs) { 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); } 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; } 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; } public boolean lt_b(double rhs) { typerror("attempt to compare string with number"); return false; }
@Override
public LuaValue lteq(LuaValue rhs) { 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); } 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; } 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; } public boolean lteq_b(double rhs) { typerror("attempt to compare string with number"); return false; }
@Override
public LuaValue gt(LuaValue rhs) { 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); } 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; } 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; } public boolean gt_b(double rhs) { typerror("attempt to compare string with number"); return false; }
@Override
public LuaValue gteq(LuaValue rhs) { 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); } 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; } 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; } public boolean gteq_b(double rhs) { typerror("attempt to compare string with number"); return false; }
// concatenation // concatenation
@Override
public LuaValue concat(LuaValue rhs) { return rhs.concatTo(this); } public LuaValue concat(LuaValue rhs) { return rhs.concatTo(this); }
@Override
public Buffer concat(Buffer rhs) { return rhs.concatTo(this); } public Buffer concat(Buffer rhs) { return rhs.concatTo(this); }
@Override
public LuaValue concatTo(LuaNumber lhs) { return concatTo(lhs.strvalue()); } public LuaValue concatTo(LuaNumber lhs) { return concatTo(lhs.strvalue()); }
@Override
public LuaValue concatTo(LuaString lhs) { public LuaValue concatTo(LuaString lhs) {
byte[] b = new byte[lhs.m_length+this.m_length]; byte[] b = new byte[lhs.m_length+this.m_length];
System.arraycopy(lhs.m_bytes, lhs.m_offset, b, 0, lhs.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 // string comparison
@Override
public int strcmp(LuaValue lhs) { return -lhs.strcmp(this); } public int strcmp(LuaValue lhs) { return -lhs.strcmp(this); }
@Override
public int strcmp(LuaString rhs) { public int strcmp(LuaString rhs) {
for (int i = 0, j = 0; i < m_length && j < rhs.m_length; ++i, ++j) { 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]) { 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; return m_length-rhs.m_length;
@@ -443,18 +494,22 @@ public class LuaString extends LuaValue {
return d; return d;
} }
@Override
public int checkint() { public int checkint() {
return (int) (long) checkdouble(); return (int) (long) checkdouble();
} }
@Override
public LuaInteger checkinteger() { public LuaInteger checkinteger() {
return valueOf(checkint()); return valueOf(checkint());
} }
@Override
public long checklong() { public long checklong() {
return (long) checkdouble(); return (long) checkdouble();
} }
@Override
public double checkdouble() { public double checkdouble() {
double d = scannumber(); double d = scannumber();
if (Double.isNaN(d)) if (Double.isNaN(d))
@@ -462,10 +517,12 @@ public class LuaString extends LuaValue {
return d; return d;
} }
@Override
public LuaNumber checknumber() { public LuaNumber checknumber() {
return valueOf(checkdouble()); return valueOf(checkdouble());
} }
@Override
public LuaNumber checknumber(String msg) { public LuaNumber checknumber(String msg) {
double d = scannumber(); double d = scannumber();
if (Double.isNaN(d)) if (Double.isNaN(d))
@@ -473,11 +530,13 @@ public class LuaString extends LuaValue {
return valueOf(d); return valueOf(d);
} }
@Override
public boolean isnumber() { public boolean isnumber() {
double d = scannumber(); double d = scannumber();
return !Double.isNaN(d); return !Double.isNaN(d);
} }
@Override
public boolean isint() { public boolean isint() {
double d = scannumber(); double d = scannumber();
if (Double.isNaN(d)) if (Double.isNaN(d))
@@ -486,6 +545,7 @@ public class LuaString extends LuaValue {
return i == d; return i == d;
} }
@Override
public boolean islong() { public boolean islong() {
double d = scannumber(); double d = scannumber();
if (Double.isNaN(d)) if (Double.isNaN(d))
@@ -494,52 +554,68 @@ public class LuaString extends LuaValue {
return l == d; return l == d;
} }
@Override
public byte tobyte() { return (byte) toint(); } public byte tobyte() { return (byte) toint(); }
@Override
public char tochar() { return (char) toint(); } public char tochar() { return (char) toint(); }
@Override
public double todouble() { double d = scannumber(); return Double.isNaN(d)? 0: d; } public double todouble() { double d = scannumber(); return Double.isNaN(d)? 0: d; }
@Override
public float tofloat() { return (float) todouble(); } public float tofloat() { return (float) todouble(); }
@Override
public int toint() { return (int) tolong(); } public int toint() { return (int) tolong(); }
@Override
public long tolong() { return (long) todouble(); } public long tolong() { return (long) todouble(); }
@Override
public short toshort() { return (short) toint(); } public short toshort() { return (short) toint(); }
@Override
public double optdouble(double defval) { public double optdouble(double defval) {
return checkdouble(); return checkdouble();
} }
@Override
public int optint(int defval) { public int optint(int defval) {
return checkint(); return checkint();
} }
@Override
public LuaInteger optinteger(LuaInteger defval) { public LuaInteger optinteger(LuaInteger defval) {
return checkinteger(); return checkinteger();
} }
@Override
public long optlong(long defval) { public long optlong(long defval) {
return checklong(); return checklong();
} }
@Override
public LuaNumber optnumber(LuaNumber defval) { public LuaNumber optnumber(LuaNumber defval) {
return checknumber(); return checknumber();
} }
@Override
public LuaString optstring(LuaString defval) { public LuaString optstring(LuaString defval) {
return this; return this;
} }
@Override
public LuaValue tostring() { public LuaValue tostring() {
return this; return this;
} }
@Override
public String optjstring(String defval) { public String optjstring(String defval) {
return tojstring(); return tojstring();
} }
@Override
public LuaString strvalue() { public LuaString strvalue() {
return this; return this;
} }
@@ -547,7 +623,7 @@ public class LuaString extends LuaValue {
/** /**
* Take a substring using Java zero-based indexes for begin and end or * Take a substring using Java zero-based indexes for begin and end or
* range. * range.
* *
* @param beginIndex The zero-based index of the first character to include. * @param beginIndex The zero-based index of the first character to include.
* @param endIndex The zero-based index of position after the last * @param endIndex The zero-based index of position after the last
* character. * 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); return len >= m_length/2? valueUsing(m_bytes, off, len): valueOf(m_bytes, off, len);
} }
@Override
public int hashCode() { public int hashCode() {
return m_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 * 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 * lua's rules for string hashes. For long strings, not all bytes are
* hashed. * hashed.
* *
* @param bytes byte array containing the bytes. * @param bytes byte array containing the bytes.
* @param offset offset into the hash for the first byte. * @param offset offset into the hash for the first byte.
* @param length number of bytes starting with offset that are part of the * @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 h = length; /* seed */
int step = (length>>5)+1; /* if string is too long, don't hash all its chars */ 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 */ 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; return h;
} }
// object comparison, used in key comparison // object comparison, used in key comparison
@Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (o instanceof LuaString) { if (o instanceof LuaString) {
return raweq((LuaString) o); return raweq((LuaString) o);
@@ -592,15 +670,19 @@ public class LuaString extends LuaValue {
} }
// equality w/ metatable processing // equality w/ metatable processing
@Override
public LuaValue eq(LuaValue val) { return val.raweq(this)? TRUE: FALSE; } public LuaValue eq(LuaValue val) { return val.raweq(this)? TRUE: FALSE; }
@Override
public boolean eq_b(LuaValue val) { return val.raweq(this); } public boolean eq_b(LuaValue val) { return val.raweq(this); }
// equality w/o metatable processing // equality w/o metatable processing
@Override
public boolean raweq(LuaValue val) { public boolean raweq(LuaValue val) {
return val.raweq(this); return val.raweq(this);
} }
@Override
public boolean raweq(LuaString s) { public boolean raweq(LuaString s) {
if (this == s) if (this == s)
return true; return true;
@@ -625,7 +707,7 @@ public class LuaString extends LuaValue {
* bytes. * bytes.
*/ */
private boolean byteseq(byte[] bytes, int off, int len) { 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) { 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); writer.write(m_bytes, m_offset+i, len);
} }
@Override
public LuaValue len() { public LuaValue len() {
return LuaInteger.valueOf(m_length); return LuaInteger.valueOf(m_length);
} }
@Override
public int length() { public int length() {
return m_length; return m_length;
} }
@Override
public int rawlen() { public int rawlen() {
return m_length; return m_length;
} }
@@ -663,17 +748,19 @@ public class LuaString extends LuaValue {
return luaByte(index); return luaByte(index);
} }
@Override
public String checkjstring() { public String checkjstring() {
return tojstring(); return tojstring();
} }
@Override
public LuaString checkstring() { public LuaString checkstring() {
return this; return this;
} }
/** /**
* Convert value to an input stream. * Convert value to an input stream.
* *
* @return {@link InputStream} whose data matches the bytes in this * @return {@link InputStream} whose data matches the bytes in this
* {@link LuaString} * {@link LuaString}
*/ */
@@ -683,7 +770,7 @@ public class LuaString extends LuaValue {
/** /**
* Copy the bytes of the string into the given byte array. * Copy the bytes of the string into the given byte array.
* *
* @param strOffset offset from which to copy * @param strOffset offset from which to copy
* @param bytes destination byte array * @param bytes destination byte array
* @param arrayOffset offset in destination * @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 * Java version of strpbrk - find index of any byte that in an accept
* string. * string.
* *
* @param accept {@link LuaString} containing characters to look for. * @param accept {@link LuaString} containing characters to look for.
* @return index of first match in the {@code accept} string, or -1 if not * @return index of first match in the {@code accept} string, or -1 if not
* found. * found.
@@ -716,7 +803,7 @@ public class LuaString extends LuaValue {
/** /**
* Find the index of a byte starting at a point in this string * Find the index of a byte starting at a point in this string
* *
* @param b the byte to look for * @param b the byte to look for
* @param start the first index in the string * @param start the first index in the string
* @return index of first match found, or -1 if not found. * @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 * Find the index of a string starting at a point in this string
* *
* @param s the string to search for * @param s the string to search for
* @param start the first index in the string * @param start the first index in the string
* @return index of first match found, or -1 if not found. * @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 * Find the last index of a string in this string
* *
* @param s the string to search for * @param s the string to search for
* @return index of last match found, or -1 if not found. * @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. * Convert to Java String interpreting as utf8 characters.
* *
* @param bytes byte array in UTF8 encoding to convert * @param bytes byte array in UTF8 encoding to convert
* @param offset starting index in byte array * @param offset starting index in byte array
* @param length number of bytes to convert * @param length number of bytes to convert
@@ -786,16 +873,16 @@ public class LuaString extends LuaValue {
} }
char[] chars = new char[n]; char[] chars = new char[n];
for (i = offset, j = offset+length, n = 0; i < j;) { for (i = offset, j = offset+length, n = 0; i < j;) {
chars[n++] = (char) (((b = bytes[i++]) >= 0 || i >= j)? b chars[n++] = (char) ((b = bytes[i++]) >= 0 || i >= j? b
: (b < -32 || i+1 >= j)? (((b & 0x3f)<<6) | (bytes[i++] & 0x3f)) : b < -32 || i+1 >= j? (b & 0x3f)<<6 | bytes[i++] & 0x3f
: (((b & 0xf)<<12) | ((bytes[i++] & 0x3f)<<6) | (bytes[i++] & 0x3f))); : (b & 0xf)<<12 | (bytes[i++] & 0x3f)<<6 | bytes[i++] & 0x3f);
} }
return new String(chars); return new String(chars);
} }
/** /**
* Count the number of bytes required to encode the string as UTF-8. * 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 * @param chars Array of unicode characters to be encoded as UTF-8
* @return count of bytes needed to encode using UTF-8 * @return count of bytes needed to encode using UTF-8
* @see #encodeToUtf8(char[], int, byte[], int) * @see #encodeToUtf8(char[], int, byte[], int)
@@ -807,7 +894,7 @@ public class LuaString extends LuaValue {
char c; char c;
for (i = b = chars.length; --i >= 0;) for (i = b = chars.length; --i >= 0;)
if ((c = chars[i]) >= 0x80) if ((c = chars[i]) >= 0x80)
b += (c >= 0x800)? 2: 1; b += c >= 0x800? 2: 1;
return b; return b;
} }
@@ -817,7 +904,7 @@ public class LuaString extends LuaValue {
* <p> * <p>
* The string should be measured first with lengthAsUtf8 to make sure the * The string should be measured first with lengthAsUtf8 to make sure the
* given byte array is large enough. * given byte array is large enough.
* *
* @param chars Array of unicode characters to be encoded as UTF-8 * @param chars Array of unicode characters to be encoded as UTF-8
* @param nchars Number of characters in the array to convert. * @param nchars Number of characters in the array to convert.
* @param bytes byte array to hold the result * @param bytes byte array to hold the result
@@ -834,12 +921,12 @@ public class LuaString extends LuaValue {
if ((c = chars[i]) < 0x80) { if ((c = chars[i]) < 0x80) {
bytes[j++] = (byte) c; bytes[j++] = (byte) c;
} else if (c < 0x800) { } else if (c < 0x800) {
bytes[j++] = (byte) (0xC0 | ((c>>6) & 0x1f)); bytes[j++] = (byte) (0xC0 | c>>6 & 0x1f);
bytes[j++] = (byte) (0x80 | (c & 0x3f)); bytes[j++] = (byte) (0x80 | c & 0x3f);
} else { } else {
bytes[j++] = (byte) (0xE0 | ((c>>12) & 0x0f)); bytes[j++] = (byte) (0xE0 | c>>12 & 0x0f);
bytes[j++] = (byte) (0x80 | ((c>>6) & 0x3f)); bytes[j++] = (byte) (0x80 | c>>6 & 0x3f);
bytes[j++] = (byte) (0x80 | (c & 0x3f)); bytes[j++] = (byte) (0x80 | c & 0x3f);
} }
} }
return j-off; return j-off;
@@ -847,7 +934,7 @@ public class LuaString extends LuaValue {
/** /**
* Check that a byte sequence is valid UTF-8 * Check that a byte sequence is valid UTF-8
* *
* @return true if it is valid UTF-8, otherwise false * @return true if it is valid UTF-8, otherwise false
* @see #lengthAsUtf8(char[]) * @see #lengthAsUtf8(char[])
* @see #encodeToUtf8(char[], int, byte[], int) * @see #encodeToUtf8(char[], int, byte[], int)
@@ -856,11 +943,9 @@ public class LuaString extends LuaValue {
public boolean isValidUtf8() { public boolean isValidUtf8() {
for (int i = m_offset, j = m_offset+m_length; i < j;) { for (int i = m_offset, j = m_offset+m_length; i < j;) {
int c = m_bytes[i++]; int c = m_bytes[i++];
if (c >= 0) if (c >= 0 || (c & 0xE0) == 0xC0 && i < j && (m_bytes[i++] & 0xC0) == 0x80)
continue; continue;
if (((c & 0xE0) == 0xC0) && i < j && (m_bytes[i++] & 0xC0) == 0x80) if ((c & 0xF0) == 0xE0 && i+1 < j && (m_bytes[i++] & 0xC0) == 0x80 && (m_bytes[i++] & 0xC0) == 0x80)
continue;
if (((c & 0xF0) == 0xE0) && i+1 < j && (m_bytes[i++] & 0xC0) == 0x80 && (m_bytes[i++] & 0xC0) == 0x80)
continue; continue;
return false; 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 * convert to a number using baee 10 or base 16 if it starts with '0x', or
* NIL if it can't be converted * NIL if it can't be converted
* *
* @return IntValue, DoubleValue, or NIL depending on the content of the * @return IntValue, DoubleValue, or NIL depending on the content of the
* string. * string.
* @see LuaValue#tonumber() * @see LuaValue#tonumber()
*/ */
@Override
public LuaValue tonumber() { public LuaValue tonumber() {
double d = scannumber(); double d = scannumber();
return Double.isNaN(d)? NIL: valueOf(d); 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 * convert to a number using a supplied base, or NIL if it can't be
* converted * converted
* *
* @param base the base to use, such as 10 * @param base the base to use, such as 10
* @return IntValue, DoubleValue, or NIL depending on the content of the * @return IntValue, DoubleValue, or NIL depending on the content of the
* string. * 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 * 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. * '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 * @return double value if conversion is valid, or Double.NaN if not
*/ */
public double scannumber() { 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. * 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 * @param base the base to use between 2 and 36
* @return double value if conversion is valid, or Double.NaN if not * @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. * Scan and convert a long value, or return Double.NaN if not found.
* *
* @param base the base to use, such as 10 * @param base the base to use, such as 10
* @param start the index to start searching from * @param start the index to start searching from
* @param end the first index beyond the search range * @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) { private double scanlong(int base, int start, int end) {
long x = 0; long x = 0;
boolean neg = (m_bytes[start] == '-'); boolean neg = m_bytes[start] == '-';
for (int i = (neg? start+1: start); i < end; i++) { 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' 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)); : m_bytes[i] >= 'A' && m_bytes[i] <= 'Z'? 'A'-10: 'a'-10);
if (digit < 0 || digit >= base) if (digit < 0 || digit >= base)
return Double.NaN; return Double.NaN;
x = x*base+digit; 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. * Scan and convert a double value, or return Double.NaN if not a double.
* *
* @param start the index to start searching from * @param start the index to start searching from
* @param end the first index beyond the search range * @param end the first index beyond the search range
* @return double value if conversion is valid, or Double.NaN if not * @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 * Print the bytes of the LuaString to a PrintStream as if it were an ASCII
* string, quoting and escaping control characters. * string, quoting and escaping control characters.
* *
* @param ps PrintStream to print to. * @param ps PrintStream to print to.
*/ */
public void printToStream(PrintStream ps) { public void printToStream(PrintStream ps) {

View File

@@ -10,7 +10,7 @@
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -45,7 +45,7 @@ import java.util.Vector;
* </ul> * </ul>
* <p> * <p>
* To iterate over key-value pairs from Java, use * To iterate over key-value pairs from Java, use
* *
* <pre> * <pre>
* {@code * {@code
* LuaValue k = LuaValue.NIL; * LuaValue k = LuaValue.NIL;
@@ -57,7 +57,7 @@ import java.util.Vector;
* process( k, v ) * process( k, v )
* }} * }}
* </pre> * </pre>
* *
* <p> * <p>
* As with other types, {@link LuaTable} instances should be constructed via one * As with other types, {@link LuaTable} instances should be constructed via one
* of the table constructor methods on {@link LuaValue}: * of the table constructor methods on {@link LuaValue}:
@@ -73,7 +73,7 @@ import java.util.Vector;
* <li>{@link LuaValue#tableOf(LuaValue[], LuaValue[], Varargs)} initialize * <li>{@link LuaValue#tableOf(LuaValue[], LuaValue[], Varargs)} initialize
* array and named parts</li> * array and named parts</li>
* </ul> * </ul>
* *
* @see LuaValue * @see LuaValue
*/ */
public class LuaTable extends LuaValue implements Metatable { public class LuaTable extends LuaValue implements Metatable {
@@ -100,7 +100,7 @@ public class LuaTable extends LuaValue implements Metatable {
/** /**
* Construct table with preset capacity. * Construct table with preset capacity.
* *
* @param narray capacity of array part * @param narray capacity of array part
* @param nhash capacity of hash 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. * Construct table with named and unnamed parts.
* *
* @param named Named elements in order * @param named Named elements in order
* {@code key-a, value-a, key-b, value-b, ... } * {@code key-a, value-a, key-b, value-b, ... }
* @param unnamed Unnamed elements in order {@code value-1, value-2, ... } * @param unnamed Unnamed elements in order {@code value-1, value-2, ... }
* @param lastarg Additional unnamed values beyond {@code unnamed.length} * @param lastarg Additional unnamed values beyond {@code unnamed.length}
*/ */
public LuaTable(LuaValue[] named, LuaValue[] unnamed, Varargs lastarg) { public LuaTable(LuaValue[] named, LuaValue[] unnamed, Varargs lastarg) {
int nn = (named != null? named.length: 0); int nn = named != null? named.length: 0;
int nu = (unnamed != null? unnamed.length: 0); int nu = unnamed != null? unnamed.length: 0;
int nl = (lastarg != null? lastarg.narg(): 0); int nl = lastarg != null? lastarg.narg(): 0;
presize(nu+nl, nn>>1); presize(nu+nl, nn>>1);
for (int i = 0; i < nu; i++) for (int i = 0; i < nu; i++)
rawset(i+1, unnamed[i]); rawset(i+1, unnamed[i]);
@@ -133,7 +133,7 @@ public class LuaTable extends LuaValue implements Metatable {
/** /**
* Construct table of unnamed elements. * Construct table of unnamed elements.
* *
* @param varargs Unnamed elements in order {@code value-1, value-2, ... } * @param varargs Unnamed elements in order {@code value-1, value-2, ... }
*/ */
public LuaTable(Varargs varargs) { public LuaTable(Varargs varargs) {
@@ -142,7 +142,7 @@ public class LuaTable extends LuaValue implements Metatable {
/** /**
* Construct table of unnamed elements. * Construct table of unnamed elements.
* *
* @param varargs Unnamed elements in order {@code value-1, value-2, ... } * @param varargs Unnamed elements in order {@code value-1, value-2, ... }
* @param firstarg the index in varargs of the first argument to include in * @param firstarg the index in varargs of the first argument to include in
* the table * the table
@@ -156,26 +156,32 @@ public class LuaTable extends LuaValue implements Metatable {
set(i, varargs.arg(i+nskip)); set(i, varargs.arg(i+nskip));
} }
@Override
public int type() { public int type() {
return LuaValue.TTABLE; return LuaValue.TTABLE;
} }
@Override
public String typename() { public String typename() {
return "table"; return "table";
} }
@Override
public boolean istable() { public boolean istable() {
return true; return true;
} }
@Override
public LuaTable checktable() { public LuaTable checktable() {
return this; return this;
} }
@Override
public LuaTable opttable(LuaTable defval) { public LuaTable opttable(LuaTable defval) {
return this; return this;
} }
@Override
public void presize(int narray) { public void presize(int narray) {
if (narray > array.length) if (narray > array.length)
array = resize(array, 1<<log2(narray)); array = resize(array, 1<<log2(narray));
@@ -185,8 +191,8 @@ public class LuaTable extends LuaValue implements Metatable {
if (nhash > 0 && nhash < MIN_HASH_CAPACITY) if (nhash > 0 && nhash < MIN_HASH_CAPACITY)
nhash = MIN_HASH_CAPACITY; nhash = MIN_HASH_CAPACITY;
// Size of both parts must be a power of two. // Size of both parts must be a power of two.
array = (narray > 0? new LuaValue[1<<log2(narray)]: NOVALS); array = narray > 0? new LuaValue[1<<log2(narray)]: NOVALS;
hash = (nhash > 0? new Slot[1<<log2(nhash)]: NOBUCKETS); hash = nhash > 0? new Slot[1<<log2(nhash)]: NOBUCKETS;
hashEntries = 0; hashEntries = 0;
} }
@@ -199,7 +205,7 @@ public class LuaTable extends LuaValue implements Metatable {
/** /**
* Get the length of the array part of the table. * Get the length of the array part of the table.
* *
* @return length of the array part, does not relate to count of objects in * @return length of the array part, does not relate to count of objects in
* the table. * the table.
*/ */
@@ -207,38 +213,43 @@ public class LuaTable extends LuaValue implements Metatable {
/** /**
* Get the length of the hash part of the table. * Get the length of the hash part of the table.
* *
* @return length of the hash part, does not relate to count of objects in * @return length of the hash part, does not relate to count of objects in
* the table. * the table.
*/ */
protected int getHashLength() { return hash.length; } protected int getHashLength() { return hash.length; }
@Override
public LuaValue getmetatable() { 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) { public LuaValue setmetatable(LuaValue metatable) {
boolean hadWeakKeys = m_metatable != null && m_metatable.useWeakKeys(); boolean hadWeakKeys = m_metatable != null && m_metatable.useWeakKeys();
boolean hadWeakValues = m_metatable != null && m_metatable.useWeakValues(); boolean hadWeakValues = m_metatable != null && m_metatable.useWeakValues();
m_metatable = metatableOf(metatable); m_metatable = metatableOf(metatable);
if ((hadWeakKeys != (m_metatable != null && m_metatable.useWeakKeys())) if (hadWeakKeys != (m_metatable != null && m_metatable.useWeakKeys())
|| (hadWeakValues != (m_metatable != null && m_metatable.useWeakValues()))) { || hadWeakValues != (m_metatable != null && m_metatable.useWeakValues())) {
// force a rehash // force a rehash
rehash(0); rehash(0);
} }
return this; return this;
} }
@Override
public LuaValue get(int key) { public LuaValue get(int key) {
LuaValue v = rawget(key); LuaValue v = rawget(key);
return v.isnil() && m_metatable != null? gettable(this, valueOf(key)): v; return v.isnil() && m_metatable != null? gettable(this, valueOf(key)): v;
} }
@Override
public LuaValue get(LuaValue key) { public LuaValue get(LuaValue key) {
LuaValue v = rawget(key); LuaValue v = rawget(key);
return v.isnil() && m_metatable != null? gettable(this, key): v; return v.isnil() && m_metatable != null? gettable(this, key): v;
} }
@Override
public LuaValue rawget(int key) { public LuaValue rawget(int key) {
if (key > 0 && key <= array.length) { if (key > 0 && key <= array.length) {
LuaValue v = m_metatable == null? array[key-1]: m_metatable.arrayget(array, key-1); 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)); return hashget(LuaInteger.valueOf(key));
} }
@Override
public LuaValue rawget(LuaValue key) { public LuaValue rawget(LuaValue key) {
if (key.isinttype()) { if (key.isinttype()) {
int ikey = key.toint(); int ikey = key.toint();
@@ -270,12 +282,14 @@ public class LuaTable extends LuaValue implements Metatable {
return NIL; return NIL;
} }
@Override
public void set(int key, LuaValue value) { public void set(int key, LuaValue value) {
if (m_metatable == null || !rawget(key).isnil() || !settable(this, LuaInteger.valueOf(key), value)) if (m_metatable == null || !rawget(key).isnil() || !settable(this, LuaInteger.valueOf(key), value))
rawset(key, value); rawset(key, value);
} }
/** caller must ensure key is not nil */ /** caller must ensure key is not nil */
@Override
public void set(LuaValue key, LuaValue value) { public void set(LuaValue key, LuaValue value) {
if (key == null || !key.isvalidkey() && !metatag(NEWINDEX).isfunction()) if (key == null || !key.isvalidkey() && !metatag(NEWINDEX).isfunction())
throw new LuaError("value ('" + key + "') can not be used as a table index"); 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); rawset(key, value);
} }
@Override
public void rawset(int key, LuaValue value) { public void rawset(int key, LuaValue value) {
if (!arrayset(key, value)) if (!arrayset(key, value))
hashset(LuaInteger.valueOf(key), value); hashset(LuaInteger.valueOf(key), value);
} }
/** caller must ensure key is not nil */ /** caller must ensure key is not nil */
@Override
public void rawset(LuaValue key, LuaValue value) { public void rawset(LuaValue key, LuaValue value) {
if (!key.isinttype() || !arrayset(key.toint(), value)) if (!key.isinttype() || !arrayset(key.toint(), value))
hashset(key, value); hashset(key, value);
@@ -297,7 +313,7 @@ public class LuaTable extends LuaValue implements Metatable {
/** Set an array element */ /** Set an array element */
private boolean arrayset(int key, LuaValue value) { private boolean arrayset(int key, LuaValue value) {
if (key > 0 && key <= array.length) { 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 true;
} }
return false; return false;
@@ -305,7 +321,7 @@ public class LuaTable extends LuaValue implements Metatable {
/** /**
* Remove the element at a position in a list-table * Remove the element at a position in a list-table
* *
* @param pos the position to remove * @param pos the position to remove
* @return The removed item, or {@link #NONE} if not removed * @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 * Insert an element at a position in a list-table
* *
* @param pos the position to remove * @param pos the position to remove
* @param value The value to insert * @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} * Concatenate the contents of a table efficiently, using {@link Buffer}
* *
* @param sep {@link LuaString} separater to apply between elements * @param sep {@link LuaString} separater to apply between elements
* @param i the first element index * @param i the first element index
* @param j the last element index, inclusive * @param j the last element index, inclusive
@@ -359,6 +375,7 @@ public class LuaTable extends LuaValue implements Metatable {
return sb.tostring(); return sb.tostring();
} }
@Override
public int length() { public int length() {
if (m_metatable != null) { if (m_metatable != null) {
LuaValue len = len(); LuaValue len = len();
@@ -369,6 +386,7 @@ public class LuaTable extends LuaValue implements Metatable {
return rawlen(); return rawlen();
} }
@Override
public LuaValue len() { public LuaValue len() {
final LuaValue h = metatag(LEN); final LuaValue h = metatag(LEN);
if (h.toboolean()) if (h.toboolean())
@@ -376,6 +394,7 @@ public class LuaTable extends LuaValue implements Metatable {
return LuaInteger.valueOf(rawlen()); return LuaInteger.valueOf(rawlen());
} }
@Override
public int rawlen() { public int rawlen() {
int a = getArrayLength(); int a = getArrayLength();
int n = a+1, m = 0; 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 * Get the next element after a particular key in the table
* *
* @return key,value or nil * @return key,value or nil
*/ */
@Override
public Varargs next(LuaValue key) { public Varargs next(LuaValue key) {
int i = 0; int i = 0;
do { 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 * Get the next element after a particular key in the contiguous array part
* of a table * of a table
* *
* @return key,value or none * @return key,value or none
*/ */
@Override
public Varargs inext(LuaValue key) { public Varargs inext(LuaValue key) {
int k = key.checkint()+1; int k = key.checkint()+1;
LuaValue v = rawget(k); LuaValue v = rawget(k);
@@ -469,7 +490,7 @@ public class LuaTable extends LuaValue implements Metatable {
/** /**
* Set a hashtable value * Set a hashtable value
* *
* @param key key to set * @param key key to set
* @param value value to set * @param value value to set
*/ */
@@ -499,8 +520,8 @@ public class LuaTable extends LuaValue implements Metatable {
} }
index = hashSlot(key); index = hashSlot(key);
} }
Slot entry = (m_metatable != null)? m_metatable.entry(key, value): defaultEntry(key, value); Slot entry = m_metatable != null? m_metatable.entry(key, value): defaultEntry(key, value);
hash[index] = (hash[index] != null)? hash[index].add(entry): entry; hash[index] = hash[index] != null? hash[index].add(entry): entry;
++hashEntries; ++hashEntries;
} }
} }
@@ -515,7 +536,7 @@ public class LuaTable extends LuaValue implements Metatable {
/** /**
* Find the hashtable slot index to use. * Find the hashtable slot index to use.
* *
* @param key the key to look for * @param key the key to look for
* @param hashMask N-1 where N is the number of hash slots (must be power of * @param hashMask N-1 where N is the number of hash slots (must be power of
* 2) * 2)
@@ -536,7 +557,7 @@ public class LuaTable extends LuaValue implements Metatable {
/** /**
* Find the hashtable slot to use * Find the hashtable slot to use
* *
* @param key key to look for * @param key key to look for
* @return slot to use * @return slot to use
*/ */
@@ -564,8 +585,8 @@ public class LuaTable extends LuaValue implements Metatable {
private int countHashKeys() { private int countHashKeys() {
int keys = 0; int keys = 0;
for (int i = 0; i < hash.length; ++i) { for (Slot element : hash) {
for (Slot slot = hash[i]; slot != null; slot = slot.rest()) { for (Slot slot = element; slot != null; slot = slot.rest()) {
if (slot.first() != null) if (slot.first() != null)
keys++; keys++;
} }
@@ -710,7 +731,7 @@ public class LuaTable extends LuaValue implements Metatable {
if (total*2 < 1<<log) { if (total*2 < 1<<log) {
// Not enough integer keys. // Not enough integer keys.
break; break;
} else if (keys >= (1<<(log-1))) { } else if (keys >= 1<<log-1) {
newArraySize = 1<<log; newArraySize = 1<<log;
} }
} }
@@ -741,14 +762,14 @@ public class LuaTable extends LuaValue implements Metatable {
newArray = array; 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 oldCapacity = oldHash.length;
final int newCapacity; final int newCapacity;
final int newHashMask; final int newHashMask;
if (newHashSize > 0) { if (newHashSize > 0) {
// round up to next power of 2. // 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; newHashMask = newCapacity-1;
newHash = new Slot[newCapacity]; newHash = new Slot[newCapacity];
} else { } else {
@@ -785,7 +806,7 @@ public class LuaTable extends LuaValue implements Metatable {
} else { } else {
newEntry = defaultEntry(valueOf(i), v); 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; hashEntries -= movingToArray;
} }
@Override
public Slot entry(LuaValue key, LuaValue value) { public Slot entry(LuaValue key, LuaValue value) {
return defaultEntry(key, value); return defaultEntry(key, value);
} }
@@ -828,11 +850,11 @@ public class LuaTable extends LuaValue implements Metatable {
// //
/** /**
* Sort the table using a comparator. * Sort the table using a comparator.
* *
* @param comparator {@link LuaValue} to be called to compare elements. * @param comparator {@link LuaValue} to be called to compare elements.
*/ */
public void sort(LuaValue comparator) { 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()); throw new LuaError("array too big: " + len().tolong());
if (m_metatable != null && m_metatable.useWeakValues()) { if (m_metatable != null && m_metatable.useWeakValues()) {
dropWeakArrayValues(); 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 * This may be deprecated in a future release. It is recommended to count
* via iteration over next() instead * via iteration over next() instead
* *
* @return count of keys in the table * @return count of keys in the table
*/ */
public int keyCount() { 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 * This may be deprecated in a future release. It is recommended to use
* next() instead * next() instead
* *
* @return array of keys in the table * @return array of keys in the table
*/ */
public LuaValue[] keys() { public LuaValue[] keys() {
@@ -919,8 +941,10 @@ public class LuaTable extends LuaValue implements Metatable {
} }
// equality w/ metatable processing // equality w/ metatable processing
@Override
public LuaValue eq(LuaValue val) { return eq_b(val)? TRUE: FALSE; } public LuaValue eq(LuaValue val) { return eq_b(val)? TRUE: FALSE; }
@Override
public boolean eq_b(LuaValue val) { public boolean eq_b(LuaValue val) {
if (this == val) if (this == val)
return true; return true;
@@ -1049,42 +1073,52 @@ public class LuaTable extends LuaValue implements Metatable {
this.next = next; this.next = next;
} }
@Override
public LuaValue key() { public LuaValue key() {
return entry.key(); return entry.key();
} }
@Override
public int keyindex(int hashMask) { public int keyindex(int hashMask) {
return entry.keyindex(hashMask); return entry.keyindex(hashMask);
} }
@Override
public LuaValue value() { public LuaValue value() {
return entry.value(); return entry.value();
} }
@Override
public Varargs toVarargs() { public Varargs toVarargs() {
return entry.toVarargs(); return entry.toVarargs();
} }
@Override
public StrongSlot first() { public StrongSlot first() {
return entry; return entry;
} }
@Override
public StrongSlot find(LuaValue key) { public StrongSlot find(LuaValue key) {
return entry.keyeq(key)? this: null; return entry.keyeq(key)? this: null;
} }
@Override
public boolean keyeq(LuaValue key) { public boolean keyeq(LuaValue key) {
return entry.keyeq(key); return entry.keyeq(key);
} }
@Override
public Slot rest() { public Slot rest() {
return next; return next;
} }
@Override
public int arraykey(int max) { public int arraykey(int max) {
return entry.arraykey(max); return entry.arraykey(max);
} }
@Override
public Slot set(StrongSlot target, LuaValue value) { public Slot set(StrongSlot target, LuaValue value) {
if (target == this) { if (target == this) {
entry = entry.set(value); entry = entry.set(value);
@@ -1094,10 +1128,12 @@ public class LuaTable extends LuaValue implements Metatable {
} }
} }
@Override
public Slot add(Slot entry) { public Slot add(Slot entry) {
return setnext(next.add(entry)); return setnext(next.add(entry));
} }
@Override
public Slot remove(StrongSlot target) { public Slot remove(StrongSlot target) {
if (this == target) { if (this == target) {
return new DeadSlot(key(), next); return new DeadSlot(key(), next);
@@ -1107,9 +1143,10 @@ public class LuaTable extends LuaValue implements Metatable {
return this; return this;
} }
@Override
public Slot relink(Slot rest) { public Slot relink(Slot rest) {
// This method is (only) called during rehash, so it must not change this.next. // 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. // 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() { public String toString() {
return entry + "; " + next; return entry + "; " + next;
} }
@@ -1129,26 +1167,32 @@ public class LuaTable extends LuaValue implements Metatable {
/** /**
* Base class for regular entries. * Base class for regular entries.
* *
* <p> * <p>
* If the key may be an integer, the {@link #arraykey(int)} method must be * If the key may be an integer, the {@link #arraykey(int)} method must be
* overridden to handle that case. * overridden to handle that case.
*/ */
static abstract class Entry extends Varargs implements StrongSlot { static abstract class Entry extends Varargs implements StrongSlot {
@Override
public abstract LuaValue key(); public abstract LuaValue key();
@Override
public abstract LuaValue value(); public abstract LuaValue value();
abstract Entry set(LuaValue value); abstract Entry set(LuaValue value);
@Override
public abstract boolean keyeq(LuaValue key); public abstract boolean keyeq(LuaValue key);
@Override
public abstract int keyindex(int hashMask); public abstract int keyindex(int hashMask);
@Override
public int arraykey(int max) { public int arraykey(int max) {
return 0; return 0;
} }
@Override
public LuaValue arg(int i) { public LuaValue arg(int i) {
switch (i) { switch (i) {
case 1: case 1:
@@ -1159,6 +1203,7 @@ public class LuaTable extends LuaValue implements Metatable {
return NIL; return NIL;
} }
@Override
public int narg() { public int narg() {
return 2; return 2;
} }
@@ -1166,14 +1211,17 @@ public class LuaTable extends LuaValue implements Metatable {
/** /**
* Subclasses should redefine as "return this;" whenever possible. * Subclasses should redefine as "return this;" whenever possible.
*/ */
@Override
public Varargs toVarargs() { public Varargs toVarargs() {
return varargsOf(key(), value()); return varargsOf(key(), value());
} }
@Override
public LuaValue arg1() { public LuaValue arg1() {
return key(); return key();
} }
@Override
public Varargs subargs(int start) { public Varargs subargs(int start) {
switch (start) { switch (start) {
case 1: case 1:
@@ -1184,32 +1232,39 @@ public class LuaTable extends LuaValue implements Metatable {
return NONE; return NONE;
} }
@Override
public StrongSlot first() { public StrongSlot first() {
return this; return this;
} }
@Override
public Slot rest() { public Slot rest() {
return null; return null;
} }
@Override
public StrongSlot find(LuaValue key) { public StrongSlot find(LuaValue key) {
return keyeq(key)? this: null; return keyeq(key)? this: null;
} }
@Override
public Slot set(StrongSlot target, LuaValue value) { public Slot set(StrongSlot target, LuaValue value) {
return set(value); return set(value);
} }
@Override
public Slot add(Slot entry) { public Slot add(Slot entry) {
return new LinkSlot(this, entry); return new LinkSlot(this, entry);
} }
@Override
public Slot remove(StrongSlot target) { public Slot remove(StrongSlot target) {
return new DeadSlot(key(), null); return new DeadSlot(key(), null);
} }
@Override
public Slot relink(Slot rest) { 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; this.value = value;
} }
@Override
public LuaValue key() { public LuaValue key() {
return key; return key;
} }
@Override
public LuaValue value() { public LuaValue value() {
return value; return value;
} }
@Override
public Entry set(LuaValue value) { public Entry set(LuaValue value) {
this.value = value; this.value = value;
return this; return this;
} }
@Override
public Varargs toVarargs() { public Varargs toVarargs() {
return this; return this;
} }
@Override
public int keyindex(int hashMask) { public int keyindex(int hashMask) {
return hashSlot(key, hashMask); return hashSlot(key, hashMask);
} }
@Override
public boolean keyeq(LuaValue key) { public boolean keyeq(LuaValue key) {
return key.raweq(this.key); return key.raweq(this.key);
} }
@@ -1257,27 +1318,33 @@ public class LuaTable extends LuaValue implements Metatable {
this.value = value; this.value = value;
} }
@Override
public LuaValue key() { public LuaValue key() {
return valueOf(key); return valueOf(key);
} }
@Override
public int arraykey(int max) { public int arraykey(int max) {
return (key >= 1 && key <= max)? key: 0; return key >= 1 && key <= max? key: 0;
} }
@Override
public LuaValue value() { public LuaValue value() {
return value; return value;
} }
@Override
public Entry set(LuaValue value) { public Entry set(LuaValue value) {
this.value = value; this.value = value;
return this; return this;
} }
@Override
public int keyindex(int mask) { public int keyindex(int mask) {
return hashmod(LuaInteger.hashCode(key), mask); return hashmod(LuaInteger.hashCode(key), mask);
} }
@Override
public boolean keyeq(LuaValue key) { public boolean keyeq(LuaValue key) {
return key.raweq(this.key); return key.raweq(this.key);
} }
@@ -1296,14 +1363,17 @@ public class LuaTable extends LuaValue implements Metatable {
this.value = value; this.value = value;
} }
@Override
public LuaValue key() { public LuaValue key() {
return key; return key;
} }
@Override
public LuaValue value() { public LuaValue value() {
return valueOf(value); return valueOf(value);
} }
@Override
public Entry set(LuaValue value) { public Entry set(LuaValue value) {
if (value.type() == TNUMBER) { if (value.type() == TNUMBER) {
LuaValue n = value.tonumber(); LuaValue n = value.tonumber();
@@ -1315,10 +1385,12 @@ public class LuaTable extends LuaValue implements Metatable {
return new NormalEntry(this.key, value); return new NormalEntry(this.key, value);
} }
@Override
public int keyindex(int mask) { public int keyindex(int mask) {
return hashSlot(key, mask); return hashSlot(key, mask);
} }
@Override
public boolean keyeq(LuaValue key) { public boolean keyeq(LuaValue key) {
return key.raweq(this.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); return (LuaValue) (key instanceof WeakReference? ((WeakReference) key).get(): key);
} }
@Override
public int keyindex(int hashMask) { public int keyindex(int hashMask) {
// Not needed: this entry will be dropped during rehash. // Not needed: this entry will be dropped during rehash.
return 0; return 0;
} }
@Override
public StrongSlot first() { public StrongSlot first() {
return null; return null;
} }
@Override
public StrongSlot find(LuaValue key) { public StrongSlot find(LuaValue key) {
return null; return null;
} }
@Override
public boolean keyeq(LuaValue key) { public boolean keyeq(LuaValue key) {
LuaValue k = key(); LuaValue k = key();
return k != null && key.raweq(k); return k != null && key.raweq(k);
} }
@Override
public Slot rest() { public Slot rest() {
return next; return next;
} }
@Override
public int arraykey(int max) { public int arraykey(int max) {
return -1; return -1;
} }
@Override
public Slot set(StrongSlot target, LuaValue value) { 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() != null) {
// if key hasn't been garbage collected, it is still potentially a valid argument // if key hasn't been garbage collected, it is still potentially a valid argument
// to next(), so we can't drop this entry yet. // 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) { 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) { public Slot remove(StrongSlot target) {
if (key() != null) { if (key() != null) {
next = next.remove(target); next = next.remove(target);
@@ -1393,10 +1474,12 @@ public class LuaTable extends LuaValue implements Metatable {
} }
} }
@Override
public Slot relink(Slot rest) { public Slot relink(Slot rest) {
return rest; return rest;
} }
@Override
public String toString() { public String toString() {
StringBuffer buf = new StringBuffer(); StringBuffer buf = new StringBuffer();
buf.append("<dead"); buf.append("<dead");
@@ -1412,28 +1495,33 @@ public class LuaTable extends LuaValue implements Metatable {
} }
return buf.toString(); return buf.toString();
} }
}; }
private static final Slot[] NOBUCKETS = {}; private static final Slot[] NOBUCKETS = {};
// Metatable operations // Metatable operations
@Override
public boolean useWeakKeys() { public boolean useWeakKeys() {
return false; return false;
} }
@Override
public boolean useWeakValues() { public boolean useWeakValues() {
return false; return false;
} }
@Override
public LuaValue toLuaValue() { public LuaValue toLuaValue() {
return this; return this;
} }
@Override
public LuaValue wrap(LuaValue value) { public LuaValue wrap(LuaValue value) {
return value; return value;
} }
@Override
public LuaValue arrayget(LuaValue[] array, int index) { public LuaValue arrayget(LuaValue[] array, int index) {
return array[index]; return array[index];
} }

View File

@@ -10,7 +10,7 @@
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * 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 * 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. * the garbage collector must run for the thread to be garbage collected.
* *
* *
* @see LuaValue * @see LuaValue
* @see org.luaj.vm2.lib.jse.JsePlatform * @see org.luaj.vm2.lib.jse.JsePlatform
* @see org.luaj.vm2.lib.jme.JmePlatform * @see org.luaj.vm2.lib.jme.JmePlatform
@@ -112,7 +112,7 @@ public class LuaThread extends LuaValue {
/** /**
* Create a LuaThread around a function and environment * Create a LuaThread around a function and environment
* *
* @param func The function to execute * @param func The function to execute
*/ */
public LuaThread(Globals globals, LuaValue func) { public LuaThread(Globals globals, LuaValue func) {
@@ -121,26 +121,32 @@ public class LuaThread extends LuaValue {
this.globals = globals; this.globals = globals;
} }
@Override
public int type() { public int type() {
return LuaValue.TTHREAD; return LuaValue.TTHREAD;
} }
@Override
public String typename() { public String typename() {
return "thread"; return "thread";
} }
@Override
public boolean isthread() { public boolean isthread() {
return true; return true;
} }
@Override
public LuaThread optthread(LuaThread defval) { public LuaThread optthread(LuaThread defval) {
return this; return this;
} }
@Override
public LuaThread checkthread() { public LuaThread checkthread() {
return this; return this;
} }
@Override
public LuaValue getmetatable() { public LuaValue getmetatable() {
return s_metatable; return s_metatable;
} }
@@ -184,6 +190,7 @@ public class LuaThread extends LuaValue {
this.function = function; this.function = function;
} }
@Override
public synchronized void run() { public synchronized void run() {
try { try {
Varargs a = this.args; Varargs a = this.args;
@@ -212,8 +219,8 @@ public class LuaThread extends LuaValue {
previous_thread.state.status = STATUS_NORMAL; previous_thread.state.status = STATUS_NORMAL;
this.status = STATUS_RUNNING; this.status = STATUS_RUNNING;
this.wait(); this.wait();
return (this.error != null? LuaValue.varargsOf(LuaValue.FALSE, LuaValue.valueOf(this.error)) return this.error != null? LuaValue.varargsOf(LuaValue.FALSE, LuaValue.valueOf(this.error))
: LuaValue.varargsOf(LuaValue.TRUE, this.result)); : LuaValue.varargsOf(LuaValue.TRUE, this.result);
} catch (InterruptedException ie) { } catch (InterruptedException ie) {
throw new OrphanedThread(); throw new OrphanedThread();
} finally { } finally {

View File

@@ -10,7 +10,7 @@
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -35,18 +35,22 @@ public class LuaUserdata extends LuaValue {
m_metatable = metatable; m_metatable = metatable;
} }
@Override
public String tojstring() { public String tojstring() {
return String.valueOf(m_instance); return String.valueOf(m_instance);
} }
@Override
public int type() { public int type() {
return LuaValue.TUSERDATA; return LuaValue.TUSERDATA;
} }
@Override
public String typename() { public String typename() {
return "userdata"; return "userdata";
} }
@Override
public int hashCode() { public int hashCode() {
return m_instance.hashCode(); return m_instance.hashCode();
} }
@@ -55,50 +59,63 @@ public class LuaUserdata extends LuaValue {
return m_instance; return m_instance;
} }
@Override
public boolean isuserdata() { return true; } public boolean isuserdata() { return true; }
@Override
public boolean isuserdata(Class c) { return c.isAssignableFrom(m_instance.getClass()); } public boolean isuserdata(Class c) { return c.isAssignableFrom(m_instance.getClass()); }
@Override
public Object touserdata() { return m_instance; } public Object touserdata() { return m_instance; }
@Override
public Object touserdata(Class c) { return c.isAssignableFrom(m_instance.getClass())? m_instance: null; } public Object touserdata(Class c) { return c.isAssignableFrom(m_instance.getClass())? m_instance: null; }
@Override
public Object optuserdata(Object defval) { return m_instance; } public Object optuserdata(Object defval) { return m_instance; }
@Override
public Object optuserdata(Class c, Object defval) { public Object optuserdata(Class c, Object defval) {
if (!c.isAssignableFrom(m_instance.getClass())) if (!c.isAssignableFrom(m_instance.getClass()))
typerror(c.getName()); typerror(c.getName());
return m_instance; return m_instance;
} }
@Override
public LuaValue getmetatable() { public LuaValue getmetatable() {
return m_metatable; return m_metatable;
} }
@Override
public LuaValue setmetatable(LuaValue metatable) { public LuaValue setmetatable(LuaValue metatable) {
this.m_metatable = metatable; this.m_metatable = metatable;
return this; return this;
} }
@Override
public Object checkuserdata() { public Object checkuserdata() {
return m_instance; return m_instance;
} }
@Override
public Object checkuserdata(Class c) { public Object checkuserdata(Class c) {
if (c.isAssignableFrom(m_instance.getClass())) if (c.isAssignableFrom(m_instance.getClass()))
return m_instance; return m_instance;
return typerror(c.getName()); return typerror(c.getName());
} }
@Override
public LuaValue get(LuaValue key) { public LuaValue get(LuaValue key) {
return m_metatable != null? gettable(this, key): NIL; return m_metatable != null? gettable(this, key): NIL;
} }
@Override
public void set(LuaValue key, LuaValue value) { public void set(LuaValue key, LuaValue value) {
if (m_metatable == null || !settable(this, key, value)) if (m_metatable == null || !settable(this, key, value))
error("cannot set " + key + " for userdata"); error("cannot set " + key + " for userdata");
} }
@Override
public boolean equals(Object val) { public boolean equals(Object val) {
if (this == val) if (this == val)
return true; return true;
@@ -109,8 +126,10 @@ public class LuaUserdata extends LuaValue {
} }
// equality w/ metatable processing // equality w/ metatable processing
@Override
public LuaValue eq(LuaValue val) { return eq_b(val)? TRUE: FALSE; } public LuaValue eq(LuaValue val) { return eq_b(val)? TRUE: FALSE; }
@Override
public boolean eq_b(LuaValue val) { public boolean eq_b(LuaValue val) {
if (val.raweq(this)) if (val.raweq(this))
return true; return true;
@@ -121,10 +140,12 @@ public class LuaUserdata extends LuaValue {
} }
// equality w/o metatable processing // equality w/o metatable processing
@Override
public boolean raweq(LuaValue val) { return val.raweq(this); } public boolean raweq(LuaValue val) { return val.raweq(this); }
@Override
public boolean raweq(LuaUserdata val) { 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 // __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 * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -29,23 +29,23 @@ import org.luaj.vm2.LuaTable.Slot;
interface Metatable { interface Metatable {
/** Return whether or not this table's keys are weak. */ /** 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. */ /** Return whether or not this table's values are weak. */
public boolean useWeakValues(); boolean useWeakValues();
/** Return this metatable as a LuaValue. */ /** Return this metatable as a LuaValue. */
public LuaValue toLuaValue(); LuaValue toLuaValue();
/** Return an instance of Slot appropriate for the given key and value. */ /** 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. */ /** 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 * Returns the value at the given index in the array, or null if it is a
* weak reference that has been dropped. * 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; this.value = value;
} }
@Override
public boolean useWeakKeys() { public boolean useWeakKeys() {
return false; return false;
} }
@Override
public boolean useWeakValues() { public boolean useWeakValues() {
return false; return false;
} }
@Override
public LuaValue toLuaValue() { public LuaValue toLuaValue() {
return value; return value;
} }
@Override
public Slot entry(LuaValue key, LuaValue value) { public Slot entry(LuaValue key, LuaValue value) {
return LuaTable.defaultEntry(key, value); return LuaTable.defaultEntry(key, value);
} }
@Override
public LuaValue wrap(LuaValue value) { public LuaValue wrap(LuaValue value) {
return value; return value;
} }
@Override
public LuaValue arrayget(LuaValue[] array, int index) { public LuaValue arrayget(LuaValue[] array, int index) {
return array[index]; return array[index];
} }

View File

@@ -10,7 +10,7 @@
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * 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 * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * 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. * Debug helper class to pretty-print lua bytecodes.
* *
* @see Prototype * @see Prototype
* @see LuaClosure * @see LuaClosure
*/ */
@@ -114,7 +114,7 @@ public class Print extends Lua {
/** /**
* Print the code in a prototype * Print the code in a prototype
* *
* @param f the {@link Prototype} * @param f the {@link Prototype}
*/ */
public static void printCode(Prototype f) { public static void printCode(Prototype f) {
@@ -128,7 +128,7 @@ public class Print extends Lua {
/** /**
* Print an opcode in a prototype * Print an opcode in a prototype
* *
* @param f the {@link Prototype} * @param f the {@link Prototype}
* @param pc the program counter to look up and print * @param pc the program counter to look up and print
* @return pc same as above or changed * @return pc same as above or changed
@@ -139,7 +139,7 @@ public class Print extends Lua {
/** /**
* Print an opcode in a prototype * Print an opcode in a prototype
* *
* @param ps the {@link PrintStream} to print to * @param ps the {@link PrintStream} to print to
* @param f the {@link Prototype} * @param f the {@link Prototype}
* @param pc the program counter to look up and print * @param pc the program counter to look up and print
@@ -168,15 +168,15 @@ public class Print extends Lua {
case iABC: case iABC:
ps.print(a); ps.print(a);
if (getBMode(o) != OpArgN) if (getBMode(o) != OpArgN)
ps.print(" " + (ISK(b)? (-1-INDEXK(b)): b)); ps.print(" " + (ISK(b)? -1-INDEXK(b): b));
if (getCMode(o) != OpArgN) if (getCMode(o) != OpArgN)
ps.print(" " + (ISK(c)? (-1-INDEXK(c)): c)); ps.print(" " + (ISK(c)? -1-INDEXK(c): c));
break; break;
case iABx: case iABx:
if (getBMode(o) == OpArgK) { if (getBMode(o) == OpArgK) {
ps.print(a + " " + (-1-bx)); ps.print(a + " " + (-1-bx));
} else { } else {
ps.print(a + " " + (bx)); ps.print(a + " " + bx);
} }
break; break;
case iAsBx: case iAsBx:
@@ -274,9 +274,9 @@ public class Print extends Lua {
break; break;
case OP_SETLIST: case OP_SETLIST:
if (c == 0) if (c == 0)
ps.print(" ; " + ((int) code[++pc]) + " (stored in the next OP)"); ps.print(" ; " + code[++pc] + " (stored in the next OP)");
else else
ps.print(" ; " + ((int) c)); ps.print(" ; " + c);
break; break;
case OP_VARARG: case OP_VARARG:
ps.print(" ; is_vararg=" + f.is_vararg); ps.print(" ; is_vararg=" + f.is_vararg);
@@ -300,7 +300,7 @@ public class Print extends Lua {
s = "(bstring)"; s = "(bstring)";
else else
s = "(string)"; 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 ps.print("\n%" + a + " <" + s + ":" + f.linedefined + "," + f.lastlinedefined + "> (" + f.code.length
+ " instructions, " + f.code.length*4 + " bytes at " + id(f) + ")\n"); + " instructions, " + f.code.length*4 + " bytes at " + id(f) + ")\n");
ps.print(f.numparams + " param, " + f.maxstacksize + " slot, " + f.upvalues.length + " upvalue, "); 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. * Pretty-prints contents of a Prototype.
* *
* @param prototype Prototype to print. * @param prototype Prototype to print.
*/ */
public static void print(Prototype prototype) { 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. * Pretty-prints contents of a Prototype in short or long form.
* *
* @param prototype Prototype to print. * @param prototype Prototype to print.
* @param full true to print all fields, false to print short form. * @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 * Print the state of a {@link LuaClosure} that is being executed
* *
* @param cl the {@link LuaClosure} * @param cl the {@link LuaClosure}
* @param pc the program counter * @param pc the program counter
* @param stack the stack of {@link LuaValue} * @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 * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * 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. * Prototype representing compiled lua code.
* *
* <p> * <p>
* This is both a straight translation of the corresponding C type, and the main * This is both a straight translation of the corresponding C type, and the main
* data structure for execution of compiled lua bytecode. * data structure for execution of compiled lua bytecode.
* *
* <p> * <p>
* Generally, the {@link Prototype} is not constructed directly is an * Generally, the {@link Prototype} is not constructed directly is an
* intermediate result as lua code is loaded using * intermediate result as lua code is loaded using
* {@link Globals#load(java.io.Reader, String)}: * {@link Globals#load(java.io.Reader, String)}:
* *
* <pre> * <pre>
* { * {
* &#64;code * &#64;code
@@ -40,11 +40,11 @@ package org.luaj.vm2;
* globals.load(new StringReader("print 'hello'"), "main.lua").call(); * globals.load(new StringReader("print 'hello'"), "main.lua").call();
* } * }
* </pre> * </pre>
* *
* <p> * <p>
* To create a {@link Prototype} directly, a compiler such as * To create a {@link Prototype} directly, a compiler such as
* {@link org.luaj.vm2.compiler.LuaC} may be used: * {@link org.luaj.vm2.compiler.LuaC} may be used:
* *
* <pre> * <pre>
* { * {
* &#64;code * &#64;code
@@ -52,31 +52,31 @@ package org.luaj.vm2;
* Prototype p = LuaC.instance.compile(is, "script"); * Prototype p = LuaC.instance.compile(is, "script");
* } * }
* </pre> * </pre>
* *
* To simplify loading, the * To simplify loading, the
* {@link Globals#compilePrototype(java.io.InputStream, String)} method may be * {@link Globals#compilePrototype(java.io.InputStream, String)} method may be
* used: * used:
* *
* <pre> * <pre>
* { * {
* &#64;code * &#64;code
* Prototype p = globals.compileProtoytpe(is, "script"); * Prototype p = globals.compileProtoytpe(is, "script");
* } * }
* </pre> * </pre>
* *
* It may also be loaded from a {@link java.io.Reader} via * It may also be loaded from a {@link java.io.Reader} via
* {@link Globals#compilePrototype(java.io.Reader, String)}: * {@link Globals#compilePrototype(java.io.Reader, String)}:
* *
* <pre> * <pre>
* { * {
* &#64;code * &#64;code
* Prototype p = globals.compileProtoytpe(new StringReader(script), "script"); * Prototype p = globals.compileProtoytpe(new StringReader(script), "script");
* } * }
* </pre> * </pre>
* *
* To un-dump a binary file known to be a binary lua file that has been dumped * 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: * to a string, the {@link Globals.Undumper} interface may be used:
* *
* <pre> * <pre>
* { * {
* &#64;code * &#64;code
@@ -84,10 +84,10 @@ package org.luaj.vm2;
* Prototype p = globals.undumper.undump(lua_binary_file, "foo.lua"); * Prototype p = globals.undumper.undump(lua_binary_file, "foo.lua");
* } * }
* </pre> * </pre>
* *
* To execute the code represented by the {@link Prototype} it must be supplied * To execute the code represented by the {@link Prototype} it must be supplied
* to the constructor of a {@link LuaClosure}: * to the constructor of a {@link LuaClosure}:
* *
* <pre> * <pre>
* { * {
* &#64;code * &#64;code
@@ -96,17 +96,17 @@ package org.luaj.vm2;
* f.call(); * f.call();
* } * }
* </pre> * </pre>
* *
* To simplify the debugging of prototype values, the contents may be printed * To simplify the debugging of prototype values, the contents may be printed
* using {@link Print#print}: * using {@link Print#print}:
* *
* <pre> * <pre>
* {@code * {@code
* Print.print(p); * Print.print(p);
* } * }
* </pre> * </pre>
* <p> * <p>
* *
* @see LuaClosure * @see LuaClosure
* @see Globals * @see Globals
* @see Globals#undumper * @see Globals#undumper
@@ -145,13 +145,14 @@ public class Prototype {
upvalues = new Upvaldesc[n_upvalues]; upvalues = new Upvaldesc[n_upvalues];
} }
@Override
public String toString() { public String toString() {
return source + ":" + linedefined + "-" + lastlinedefined; return source + ":" + linedefined + "-" + lastlinedefined;
} }
/** /**
* Get the name of a local variable. * Get the name of a local variable.
* *
* @param number the local variable number to look up * @param number the local variable number to look up
* @param pc the program counter * @param pc the program counter
* @return the name, or null if not found * @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 * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -35,7 +35,7 @@ package org.luaj.vm2;
* <p> * <p>
* Normally, users of luaj need not concern themselves with the details of this * Normally, users of luaj need not concern themselves with the details of this
* mechanism, as it is built into the core execution framework. * mechanism, as it is built into the core execution framework.
* *
* @see Prototype * @see Prototype
* @see org.luaj.vm2.luajc.LuaJC * @see org.luaj.vm2.luajc.LuaJC
*/ */
@@ -55,8 +55,10 @@ public class TailcallVarargs extends Varargs {
this.args = LuaValue.varargsOf(object, args); this.args = LuaValue.varargsOf(object, args);
} }
@Override
public boolean isTailcall() { return true; } public boolean isTailcall() { return true; }
@Override
public Varargs eval() { public Varargs eval() {
while ( result == null ) { while ( result == null ) {
Varargs r = func.onInvoke(args); Varargs r = func.onInvoke(args);
@@ -73,24 +75,28 @@ public class TailcallVarargs extends Varargs {
return result; return result;
} }
@Override
public LuaValue arg(int i) { public LuaValue arg(int i) {
if (result == null) if (result == null)
eval(); eval();
return result.arg(i); return result.arg(i);
} }
@Override
public LuaValue arg1() { public LuaValue arg1() {
if (result == null) if (result == null)
eval(); eval();
return result.arg1(); return result.arg1();
} }
@Override
public int narg() { public int narg() {
if (result == null) if (result == null)
eval(); eval();
return result.narg(); return result.narg();
} }
@Override
public Varargs subargs(int start) { public Varargs subargs(int start) {
if (result == null) if (result == null)
eval(); eval();

View File

@@ -10,7 +10,7 @@
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * 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 * Upvalue used with Closure formulation
* <p> * <p>
* *
* @see LuaClosure * @see LuaClosure
* @see Prototype * @see Prototype
*/ */
public final class UpValue { public final class UpValue {
LuaValue[] array; // initially the stack, becomes a holder LuaValue[] array; // initially the stack, becomes a holder
int index; int index;
/** /**
* Create an upvalue relative to a stack * Create an upvalue relative to a stack
* *
* @param stack the stack * @param stack the stack
* @param index the index on the stack for the upvalue * @param index the index on the stack for the upvalue
*/ */
@@ -44,13 +44,14 @@ public final class UpValue {
this.index = index; this.index = index;
} }
@Override
public String toString() { public String toString() {
return index + "/" + array.length + " " + array[index]; return index + "/" + array.length + " " + array[index];
} }
/** /**
* Convert this upvalue to a Java String * Convert this upvalue to a Java String
* *
* @return the Java String for this upvalue. * @return the Java String for this upvalue.
* @see LuaValue#tojstring() * @see LuaValue#tojstring()
*/ */
@@ -60,22 +61,22 @@ public final class UpValue {
/** /**
* Get the value of the upvalue * Get the value of the upvalue
* *
* @return the {@link LuaValue} for this 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 * Set the value of the upvalue
* *
* @param value the {@link LuaValue} to set it to * @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 * Close this upvalue so it is no longer on the stack
*/ */
public final void close() { public void close() {
LuaValue[] old = array; LuaValue[] old = array;
array = new LuaValue[] { old[index] }; array = new LuaValue[] { old[index] };
old[index] = null; old[index] = null;

View File

@@ -10,7 +10,7 @@
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -38,6 +38,7 @@ public class Upvaldesc {
this.idx = (short) idx; this.idx = (short) idx;
} }
@Override
public String toString() { public String toString() {
return idx+(instack? " instack ": " closed ")+String.valueOf(name); 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 * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * 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 * a call such as {@code LuaValue.varargsOf(LuaValue,Varargs)} or by taking a
* portion of the args using {@code Varargs.subargs(int start)} * portion of the args using {@code Varargs.subargs(int start)}
* <p> * <p>
* *
* @see LuaValue#varargsOf(LuaValue[]) * @see LuaValue#varargsOf(LuaValue[])
* @see LuaValue#varargsOf(LuaValue, Varargs) * @see LuaValue#varargsOf(LuaValue, Varargs)
* @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). * Get the n-th argument value (1-based).
* *
* @param i the index of the argument to get, 1 is the first argument * @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. * @return Value at position i, or LuaValue.NIL if there is none.
* @see Varargs#arg1() * @see Varargs#arg1()
@@ -61,14 +61,14 @@ public abstract class Varargs {
/** /**
* Get the number of arguments, or 0 if there are none. * Get the number of arguments, or 0 if there are none.
* *
* @return number of arguments. * @return number of arguments.
*/ */
abstract public int narg(); abstract public int narg();
/** /**
* Get the first argument in the list. * Get the first argument in the list.
* *
* @return LuaValue which is first in the list, or LuaValue.NIL if there are * @return LuaValue which is first in the list, or LuaValue.NIL if there are
* no values. * no values.
* @see Varargs#arg(int) * @see Varargs#arg(int)
@@ -78,14 +78,14 @@ public abstract class Varargs {
/** /**
* Evaluate any pending tail call and return result. * Evaluate any pending tail call and return result.
* *
* @return the evaluated tail call result * @return the evaluated tail call result
*/ */
public Varargs eval() { return this; } public Varargs eval() { return this; }
/** /**
* Return true if this is a TailcallVarargs * Return true if this is a TailcallVarargs
* *
* @return true if a tail call, false otherwise * @return true if a tail call, false otherwise
*/ */
public boolean isTailcall() { return false; } public boolean isTailcall() { return false; }
@@ -96,7 +96,7 @@ public abstract class Varargs {
/** /**
* Gets the type of argument {@code i} * Gets the type of argument {@code i}
* *
* @param i the index of the argument to convert, 1 is the first argument * @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 * @return int value corresponding to one of the LuaValue integer type
* values * values
@@ -113,7 +113,7 @@ public abstract class Varargs {
/** /**
* Tests if argument i is nil. * Tests if argument i is nil.
* *
* @param i the index of the argument to test, 1 is the first argument * @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 * @return true if the argument is nil or does not exist, false otherwise
* @see LuaValue#TNIL * @see LuaValue#TNIL
@@ -122,7 +122,7 @@ public abstract class Varargs {
/** /**
* Tests if argument i is a function. * Tests if argument i is a function.
* *
* @param i the index of the argument to test, 1 is the first argument * @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 * @return true if the argument exists and is a function or closure, false
* otherwise * otherwise
@@ -134,7 +134,7 @@ public abstract class Varargs {
* Tests if argument i is a number. Since anywhere a number is required, a * 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 * string can be used that is a number, this will return true for both
* numbers and strings that can be interpreted as numbers. * numbers and strings that can be interpreted as numbers.
* *
* @param i the index of the argument to test, 1 is the first argument * @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 * @return true if the argument exists and is a number or string that can be
* interpreted as a number, false otherwise * 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 * 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. * 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 * @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 * @return true if the argument exists and is a string or number, false
* otherwise * otherwise
@@ -157,7 +157,7 @@ public abstract class Varargs {
/** /**
* Tests if argument i is a table. * Tests if argument i is a table.
* *
* @param i the index of the argument to test, 1 is the first argument * @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 * @return true if the argument exists and is a lua table, false otherwise
* @see LuaValue#TTABLE * @see LuaValue#TTABLE
@@ -166,7 +166,7 @@ public abstract class Varargs {
/** /**
* Tests if argument i is a thread. * Tests if argument i is a thread.
* *
* @param i the index of the argument to test, 1 is the first argument * @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 * @return true if the argument exists and is a lua thread, false otherwise
* @see LuaValue#TTHREAD * @see LuaValue#TTHREAD
@@ -175,7 +175,7 @@ public abstract class Varargs {
/** /**
* Tests if argument i is a userdata. * Tests if argument i is a userdata.
* *
* @param i the index of the argument to test, 1 is the first argument * @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 * @return true if the argument exists and is a userdata, false otherwise
* @see LuaValue#TUSERDATA * @see LuaValue#TUSERDATA
@@ -184,7 +184,7 @@ public abstract class Varargs {
/** /**
* Tests if a value exists at argument i. * Tests if a value exists at argument i.
* *
* @param i the index of the argument to test, 1 is the first argument * @param i the index of the argument to test, 1 is the first argument
* @return true if the argument exists, false otherwise * @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 * Return argument i as a boolean value, {@code defval} if nil, or throw a
* LuaError if any other type. * LuaError if any other type.
* *
* @param i the index of the argument to test, 1 is the first argument * @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 * @return true if argument i is boolean true, false if it is false, or
* defval if not supplied or nil * 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 * Return argument i as a closure, {@code defval} if nil, or throw a
* LuaError if any other type. * LuaError if any other type.
* *
* @param i the index of the argument to test, 1 is the first argument * @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 * @return LuaClosure if argument i is a closure, or defval if not supplied
* or nil * or nil
@@ -215,7 +215,7 @@ public abstract class Varargs {
/** /**
* Return argument i as a double, {@code defval} if nil, or throw a LuaError * Return argument i as a double, {@code defval} if nil, or throw a LuaError
* if it cannot be converted to one. * if it cannot be converted to one.
* *
* @param i the index of the argument to test, 1 is the first argument * @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 * @return java double value if argument i is a number or string that
* converts to a number, or defval if not supplied or nil * 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 * Return argument i as a function, {@code defval} if nil, or throw a
* LuaError if an incompatible type. * LuaError if an incompatible type.
* *
* @param i the index of the argument to test, 1 is the first argument * @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 * @return LuaValue that can be called if argument i is lua function or
* closure, or defval if not supplied or nil * 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, * Return argument i as a java int value, discarding any fractional part,
* {@code defval} if nil, or throw a LuaError if not a number. * {@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 * @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 * @return int value with fraction discarded and truncated if necessary if
* argument i is number, or defval if not supplied or nil * 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 * 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. * 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 * @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 * @return LuaInteger value that fits in a java int without rounding, or
* defval if not supplied or nil * 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, * Return argument i as a java long value, discarding any fractional part,
* {@code defval} if nil, or throw a LuaError if not a number. * {@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 * @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 * @return long value with fraction discarded and truncated if necessary if
* argument i is number, or defval if not supplied or nil * 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 * 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. * 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 * @param i the index of the argument to test, 1 is the first argument, or
* defval if not supplied or nil * defval if not supplied or nil
* @return LuaNumber if argument i is number or can be converted to a number * @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} * Return argument i as a java String if a string or number, {@code defval}
* if nil, or throw a LuaError if any other type * 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 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 * @return String value if argument i is a string or number, or defval if
* not supplied or nil * 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 * Return argument i as a LuaString if a string or number, {@code defval} if
* nil, or throw a LuaError if any other type * nil, or throw a LuaError if any other type
* *
* @param i the index of the argument to test, 1 is the first argument * @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 * @return LuaString value if argument i is a string or number, or defval if
* not supplied or nil * 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 * Return argument i as a LuaTable if a lua table, {@code defval} if nil, or
* throw a LuaError if any other type. * throw a LuaError if any other type.
* *
* @param i the index of the argument to test, 1 is the first argument * @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 * @return LuaTable value if a table, or defval if not supplied or nil
* @exception LuaError if the argument is not a lua table * @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, * Return argument i as a LuaThread if a lua thread, {@code defval} if nil,
* or throw a LuaError if any other type. * or throw a LuaError if any other type.
* *
* @param i the index of the argument to test, 1 is the first argument * @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 * @return LuaThread value if a thread, or defval if not supplied or nil
* @exception LuaError if the argument is not a lua thread * @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, * Return argument i as a java Object if a userdata, {@code defval} if nil,
* or throw a LuaError if any other type. * or throw a LuaError if any other type.
* *
* @param i the index of the argument to test, 1 is the first argument * @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 * @return java Object value if argument i is a userdata, or defval if not
* supplied or nil * 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 * 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 * Class c or a subclass, {@code defval} if nil, or throw a LuaError if any
* other type. * other type.
* *
* @param i the index of the argument to test, 1 is the first argument * @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 * @param c the class to which the userdata instance must be assignable
* @return java Object value if argument i is a userdata whose instance * @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}. * 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 * @param i the index of the argument to test, 1 is the first argument
* @return LuaValue value if the argument exists, defval if not * @return LuaValue value if the argument exists, defval if not
* @exception LuaError if the argument does not exist. * @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 * Return argument i as a boolean value, or throw an error if any other
* type. * type.
* *
* @param i the index of the argument to test, 1 is the first argument * @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 * @return true if argument i is boolean true, false if it is false
* @exception LuaError if the argument is not a lua boolean * @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. * 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 * @param i the index of the argument to test, 1 is the first argument
* @return LuaClosure if argument i is a closure. * @return LuaClosure if argument i is a closure.
* @exception LuaError if the argument is not a lua 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 * Return argument i as a double, or throw an error if it cannot be
* converted to one. * converted to one.
* *
* @param i the index of the argument to test, 1 is the first argument * @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 * @return java double value if argument i is a number or string that
* converts to a number * 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 * Return argument i as a function, or throw an error if an incompatible
* type. * type.
* *
* @param i the index of the argument to test, 1 is the first argument * @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 * @return LuaValue that can be called if argument i is lua function or
* closure * 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 * Return argument i as a java int value, or throw an error if it cannot be
* converted to one. * converted to one.
* *
* @param i the index of the argument to test, 1 is the first argument * @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 * @return int value if argument i is a number or string that converts to a
* number * 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 * Return argument i as a java int value, or throw an error if not a number
* or is not representable by a java int. * or is not representable by a java int.
* *
* @param i the index of the argument to test, 1 is the first argument * @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 * @return LuaInteger value that fits in a java int without rounding
* @exception LuaError if the argument cannot be represented by a java int * @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 * Return argument i as a java long value, or throw an error if it cannot be
* converted to one. * converted to one.
* *
* @param i the index of the argument to test, 1 is the first argument * @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 * @return long value if argument i is a number or string that converts to a
* number * number
@@ -434,7 +434,7 @@ public abstract class Varargs {
/** /**
* Return argument i as a LuaNumber, or throw an error if not a number or * Return argument i as a LuaNumber, or throw an error if not a number or
* string that can be converted to a number. * string that can be converted to a number.
* *
* @param i the index of the argument to test, 1 is the first argument * @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 * @return LuaNumber if argument i is number or can be converted to a number
* @exception LuaError if the argument is not 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 * Return argument i as a java String if a string or number, or throw an
* error if any other type * error if any other type
* *
* @param i the index of the argument to test, 1 is the first argument * @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 * @return String value if argument i is a string or number
* @exception LuaError if the argument is not 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 * Return argument i as a LuaString if a string or number, or throw an error
* if any other type * if any other type
* *
* @param i the index of the argument to test, 1 is the first argument * @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 * @return LuaString value if argument i is a string or number
* @exception LuaError if the argument is not 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 * Return argument i as a LuaTable if a lua table, or throw an error if any
* other type. * other type.
* *
* @param i the index of the argument to test, 1 is the first argument * @param i the index of the argument to test, 1 is the first argument
* @return LuaTable value if a table * @return LuaTable value if a table
* @exception LuaError if the argument is not a lua 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 * Return argument i as a LuaThread if a lua thread, or throw an error if
* any other type. * any other type.
* *
* @param i the index of the argument to test, 1 is the first argument * @param i the index of the argument to test, 1 is the first argument
* @return LuaThread value if a thread * @return LuaThread value if a thread
* @exception LuaError if the argument is not a lua 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 * Return argument i as a java Object if a userdata, or throw an error if
* any other type. * any other type.
* *
* @param i the index of the argument to test, 1 is the first argument * @param i the index of the argument to test, 1 is the first argument
* @return java Object value if argument i is a userdata * @return java Object value if argument i is a userdata
* @exception LuaError if the argument is not 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 * 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. * 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 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 * @param c the class to which the userdata instance must be assignable
* @return java Object value if argument i is a userdata whose instance * @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. * 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 * @param i the index of the argument to test, 1 is the first argument
* @return LuaValue value if the argument exists * @return LuaValue value if the argument exists
* @exception LuaError if the argument does not exist. * @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 * Return argument i as a LuaValue if it is not nil, or throw an error if it
* is nil. * is nil.
* *
* @param i the index of the argument to test, 1 is the first argument * @param i the index of the argument to test, 1 is the first argument
* @return LuaValue value if the argument is not nil * @return LuaValue value if the argument is not nil
* @exception LuaError if the argument doesn't exist or evaluates to 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} * passes, or throw an error. Returns normally if the value of {@code test}
* is {@code true}, otherwise throws and argument error with the supplied * is {@code true}, otherwise throws and argument error with the supplied
* message, {@code msg}. * message, {@code msg}.
* *
* @param test user supplied assertion to test against * @param test user supplied assertion to test against
* @param i the index to report in any error message * @param i the index to report in any error message
* @param msg the error message to use when the test fails * @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. * 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 * @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 * @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 * Convert argument {@code i} to java boolean based on lua rules for boolean
* evaluation. * evaluation.
* *
* @param i the index of the argument to convert, 1 is the first argument * @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 * @return {@code false} if argument i is nil or false, otherwise
* {@code true} * {@code true}
@@ -562,7 +562,7 @@ public abstract class Varargs {
/** /**
* Return argument i as a java byte value, discarding any fractional part * Return argument i as a java byte value, discarding any fractional part
* and truncating, or 0 if not a number. * and truncating, or 0 if not a number.
* *
* @param i the index of the argument to convert, 1 is the first argument * @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 * @return byte value with fraction discarded and truncated if necessary if
* argument i is number, otherwise 0 * 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 * Return argument i as a java char value, discarding any fractional part
* and truncating, or 0 if not a number. * and truncating, or 0 if not a number.
* *
* @param i the index of the argument to convert, 1 is the first argument * @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 * @return char value with fraction discarded and truncated if necessary if
* argument i is number, otherwise 0 * 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. * 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 * @param i the index of the argument to convert, 1 is the first argument
* @return double value if argument i is number, otherwise 0 * @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 * Return argument i as a java float value, discarding excess fractional
* part and truncating, or 0 if not a number. * part and truncating, or 0 if not a number.
* *
* @param i the index of the argument to convert, 1 is the first argument * @param i the index of the argument to convert, 1 is the first argument
* @return float value with excess fraction discarded and truncated if * @return float value with excess fraction discarded and truncated if
* necessary if argument i is number, otherwise 0 * 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 * Return argument i as a java int value, discarding any fractional part and
* truncating, or 0 if not a number. * truncating, or 0 if not a number.
* *
* @param i the index of the argument to convert, 1 is the first argument * @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 * @return int value with fraction discarded and truncated if necessary if
* argument i is number, otherwise 0 * 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 * Return argument i as a java long value, discarding any fractional part
* and truncating, or 0 if not a number. * and truncating, or 0 if not a number.
* *
* @param i the index of the argument to convert, 1 is the first argument * @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 * @return long value with fraction discarded and truncated if necessary if
* argument i is number, otherwise 0 * 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. * 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 * @param i the index of the argument to convert, 1 is the first argument
* @return String value representing the type * @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 * Return argument i as a java short value, discarding any fractional part
* and truncating, or 0 if not a number. * and truncating, or 0 if not a number.
* *
* @param i the index of the argument to convert, 1 is the first argument * @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 * @return short value with fraction discarded and truncated if necessary if
* argument i is number, otherwise 0 * 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. * 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 * @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 * @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 * Return argument i as a java Object if it is a userdata whose instance
* Class c or a subclass, or null. * Class c or a subclass, or null.
* *
* @param i the index of the argument to convert, 1 is the first argument * @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 * @param c the class to which the userdata instance must be assignable
* @return java Object value if argument i is a userdata whose instance * @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. * Convert the list of varargs values to a human readable java String.
* *
* @return String value in human readable form such as {1,2}. * @return String value in human readable form such as {1,2}.
*/ */
public String tojstring() { public String tojstring() {
@@ -673,16 +673,17 @@ public abstract class Varargs {
/** /**
* Convert the value or values to a java String using Varargs.tojstring() * Convert the value or values to a java String using Varargs.tojstring()
* *
* @return String value in human readable form. * @return String value in human readable form.
* @see Varargs#tojstring() * @see Varargs#tojstring()
*/ */
@Override
public String toString() { return tojstring(); } public String toString() { return tojstring(); }
/** /**
* Create a {@code Varargs} instance containing arguments starting at index * Create a {@code Varargs} instance containing arguments starting at index
* {@code start} * {@code start}
* *
* @param start the index from which to include arguments, where 1 is the * @param start the index from which to include arguments, where 1 is the
* first argument. * first argument.
* @return Varargs containing argument { start, start+1, ... , narg-start-1 * @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. * Implementation of Varargs for use in the Varargs.subargs() function.
* *
* @see Varargs#subargs(int) * @see Varargs#subargs(int)
*/ */
static class SubVarargs extends Varargs { static class SubVarargs extends Varargs {
@@ -706,19 +707,23 @@ public abstract class Varargs {
this.end = end; this.end = end;
} }
@Override
public LuaValue arg(int i) { public LuaValue arg(int i) {
i += start-1; i += start-1;
return i >= start && i <= end? v.arg(i): LuaValue.NIL; return i >= start && i <= end? v.arg(i): LuaValue.NIL;
} }
@Override
public LuaValue arg1() { public LuaValue arg1() {
return v.arg(start); return v.arg(start);
} }
@Override
public int narg() { public int narg() {
return end+1-start; return end+1-start;
} }
@Override
public Varargs subargs(final int start) { public Varargs subargs(final int start) {
if (start == 1) if (start == 1)
return this; return this;
@@ -741,7 +746,7 @@ public abstract class Varargs {
* <p> * <p>
* This is an internal class not intended to be used directly. Instead use * This is an internal class not intended to be used directly. Instead use
* the corresponding static method on LuaValue. * the corresponding static method on LuaValue.
* *
* @see LuaValue#varargsOf(LuaValue, Varargs) * @see LuaValue#varargsOf(LuaValue, Varargs)
*/ */
static final class PairVarargs extends Varargs { static final class PairVarargs extends Varargs {
@@ -753,7 +758,7 @@ public abstract class Varargs {
* <p> * <p>
* This is an internal class not intended to be used directly. Instead * This is an internal class not intended to be used directly. Instead
* use the corresponding static method on LuaValue. * use the corresponding static method on LuaValue.
* *
* @see LuaValue#varargsOf(LuaValue, Varargs) * @see LuaValue#varargsOf(LuaValue, Varargs)
*/ */
PairVarargs(LuaValue v1, Varargs v2) { PairVarargs(LuaValue v1, Varargs v2) {
@@ -761,18 +766,22 @@ public abstract class Varargs {
this.v2 = v2; this.v2 = v2;
} }
@Override
public LuaValue arg(int i) { public LuaValue arg(int i) {
return i == 1? v1: v2.arg(i-1); return i == 1? v1: v2.arg(i-1);
} }
@Override
public int narg() { public int narg() {
return 1+v2.narg(); return 1+v2.narg();
} }
@Override
public LuaValue arg1() { public LuaValue arg1() {
return v1; return v1;
} }
@Override
public Varargs subargs(final int start) { public Varargs subargs(final int start) {
if (start == 1) if (start == 1)
return this; return this;
@@ -789,7 +798,7 @@ public abstract class Varargs {
* <p> * <p>
* This is an internal class not intended to be used directly. Instead use * This is an internal class not intended to be used directly. Instead use
* the corresponding static methods on LuaValue. * the corresponding static methods on LuaValue.
* *
* @see LuaValue#varargsOf(LuaValue[]) * @see LuaValue#varargsOf(LuaValue[])
* @see LuaValue#varargsOf(LuaValue[], Varargs) * @see LuaValue#varargsOf(LuaValue[], Varargs)
*/ */
@@ -802,7 +811,7 @@ public abstract class Varargs {
* <p> * <p>
* This is an internal class not intended to be used directly. Instead * This is an internal class not intended to be used directly. Instead
* use the corresponding static methods on LuaValue. * use the corresponding static methods on LuaValue.
* *
* @see LuaValue#varargsOf(LuaValue[]) * @see LuaValue#varargsOf(LuaValue[])
* @see LuaValue#varargsOf(LuaValue[], Varargs) * @see LuaValue#varargsOf(LuaValue[], Varargs)
*/ */
@@ -811,16 +820,20 @@ public abstract class Varargs {
this.r = r; this.r = r;
} }
@Override
public LuaValue arg(int i) { public LuaValue arg(int i) {
return i < 1? LuaValue.NIL: i <= v.length? v[i-1]: r.arg(i-v.length); return i < 1? LuaValue.NIL: i <= v.length? v[i-1]: r.arg(i-v.length);
} }
@Override
public int narg() { public int narg() {
return v.length+r.narg(); return v.length+r.narg();
} }
@Override
public LuaValue arg1() { return v.length > 0? v[0]: r.arg1(); } public LuaValue arg1() { return v.length > 0? v[0]: r.arg1(); }
@Override
public Varargs subargs(int start) { public Varargs subargs(int start) {
if (start <= 0) if (start <= 0)
LuaValue.argerror(1, "start must be > 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); return LuaValue.varargsOf(v, start-1, v.length-(start-1), r);
} }
@Override
void copyto(LuaValue[] dest, int offset, int length) { void copyto(LuaValue[] dest, int offset, int length) {
int n = Math.min(v.length, length); int n = Math.min(v.length, length);
System.arraycopy(v, 0, dest, offset, n); System.arraycopy(v, 0, dest, offset, n);
@@ -843,7 +857,7 @@ public abstract class Varargs {
* <p> * <p>
* This is an internal class not intended to be used directly. Instead use * This is an internal class not intended to be used directly. Instead use
* the corresponding static methods on LuaValue. * the corresponding static methods on LuaValue.
* *
* @see LuaValue#varargsOf(LuaValue[], int, int) * @see LuaValue#varargsOf(LuaValue[], int, int)
* @see LuaValue#varargsOf(LuaValue[], int, int, Varargs) * @see LuaValue#varargsOf(LuaValue[], int, int, Varargs)
*/ */
@@ -858,7 +872,7 @@ public abstract class Varargs {
* <p> * <p>
* This is an internal class not intended to be used directly. Instead * This is an internal class not intended to be used directly. Instead
* use the corresponding static methods on LuaValue. * use the corresponding static methods on LuaValue.
* *
* @see LuaValue#varargsOf(LuaValue[], int, int) * @see LuaValue#varargsOf(LuaValue[], int, int)
*/ */
ArrayPartVarargs(LuaValue[] v, int offset, int length) { ArrayPartVarargs(LuaValue[] v, int offset, int length) {
@@ -874,7 +888,7 @@ public abstract class Varargs {
* <p> * <p>
* This is an internal class not intended to be used directly. Instead * This is an internal class not intended to be used directly. Instead
* use the corresponding static method on LuaValue. * use the corresponding static method on LuaValue.
* *
* @see LuaValue#varargsOf(LuaValue[], int, int, Varargs) * @see LuaValue#varargsOf(LuaValue[], int, int, Varargs)
*/ */
public ArrayPartVarargs(LuaValue[] v, int offset, int length, Varargs more) { public ArrayPartVarargs(LuaValue[] v, int offset, int length, Varargs more) {
@@ -884,18 +898,22 @@ public abstract class Varargs {
this.more = more; this.more = more;
} }
@Override
public LuaValue arg(final int i) { public LuaValue arg(final int i) {
return i < 1? LuaValue.NIL: i <= length? v[offset+i-1]: more.arg(i-length); return i < 1? LuaValue.NIL: i <= length? v[offset+i-1]: more.arg(i-length);
} }
@Override
public int narg() { public int narg() {
return length+more.narg(); return length+more.narg();
} }
@Override
public LuaValue arg1() { public LuaValue arg1() {
return length > 0? v[offset]: more.arg1(); return length > 0? v[offset]: more.arg1();
} }
@Override
public Varargs subargs(int start) { public Varargs subargs(int start) {
if (start <= 0) if (start <= 0)
LuaValue.argerror(1, "start must be > 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); return LuaValue.varargsOf(v, offset+start-1, length-(start-1), more);
} }
@Override
void copyto(LuaValue[] dest, int offset, int length) { void copyto(LuaValue[] dest, int offset, int length) {
int n = Math.min(this.length, length); int n = Math.min(this.length, length);
System.arraycopy(this.v, this.offset, dest, offset, n); 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 * Copy values in a varargs into a destination array. Internal utility
* method not intended to be called directly from user code. * method not intended to be called directly from user code.
* *
* @return Varargs containing same values, but flattened. * @return Varargs containing same values, but flattened.
*/ */
void copyto(LuaValue[] dest, int offset, int length) { 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 * Return Varargs that cannot be using a shared array for the storage, and
* is flattened. Internal utility method not intended to be called directly * is flattened. Internal utility method not intended to be called directly
* from user code. * from user code.
* *
* @return Varargs containing same values, but flattened and with a new * @return Varargs containing same values, but flattened and with a new
* array if needed. * array if needed.
* @exclude * @exclude

View File

@@ -10,7 +10,7 @@
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * 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 { public class WeakTable implements Metatable {
private boolean weakkeys, weakvalues; private final boolean weakkeys, weakvalues;
private LuaValue backing; private final LuaValue backing;
public static LuaTable make(boolean weakkeys, boolean weakvalues) { public static LuaTable make(boolean weakkeys, boolean weakvalues) {
LuaString mode; LuaString mode;
@@ -49,17 +49,17 @@ public class WeakTable implements Metatable {
} else if (weakvalues) { } else if (weakvalues) {
mode = LuaString.valueOf("v"); mode = LuaString.valueOf("v");
} else { } else {
return LuaTable.tableOf(); return LuaValue.tableOf();
} }
LuaTable table = LuaTable.tableOf(); LuaTable table = LuaValue.tableOf();
LuaTable mt = LuaTable.tableOf(new LuaValue[] { LuaValue.MODE, mode }); LuaTable mt = LuaValue.tableOf(new LuaValue[] { LuaValue.MODE, mode });
table.setmetatable(mt); table.setmetatable(mt);
return table; return table;
} }
/** /**
* Construct a table with weak keys, weak values, or both * Construct a table with weak keys, weak values, or both
* *
* @param weakkeys true to let the table have weak keys * @param weakkeys true to let the table have weak keys
* @param weakvalues true to let the table have weak values * @param weakvalues true to let the table have weak values
*/ */
@@ -69,18 +69,22 @@ public class WeakTable implements Metatable {
this.backing = backing; this.backing = backing;
} }
@Override
public boolean useWeakKeys() { public boolean useWeakKeys() {
return weakkeys; return weakkeys;
} }
@Override
public boolean useWeakValues() { public boolean useWeakValues() {
return weakvalues; return weakvalues;
} }
@Override
public LuaValue toLuaValue() { public LuaValue toLuaValue() {
return backing; return backing;
} }
@Override
public Slot entry(LuaValue key, LuaValue value) { public Slot entry(LuaValue key, LuaValue value) {
value = value.strongvalue(); value = value.strongvalue();
if (value == null) if (value == null)
@@ -110,10 +114,12 @@ public class WeakTable implements Metatable {
this.next = next; this.next = next;
} }
@Override
public abstract int keyindex(int hashMask); public abstract int keyindex(int hashMask);
public abstract Slot set(LuaValue value); public abstract Slot set(LuaValue value);
@Override
public StrongSlot first() { public StrongSlot first() {
LuaValue key = strongkey(); LuaValue key = strongkey();
LuaValue value = strongvalue(); LuaValue value = strongvalue();
@@ -126,25 +132,30 @@ public class WeakTable implements Metatable {
} }
} }
@Override
public StrongSlot find(LuaValue key) { public StrongSlot find(LuaValue key) {
StrongSlot first = first(); StrongSlot first = first();
return (first != null)? first.find(key): null; return first != null? first.find(key): null;
} }
@Override
public boolean keyeq(LuaValue key) { public boolean keyeq(LuaValue key) {
StrongSlot first = first(); StrongSlot first = first();
return (first != null) && first.keyeq(key); return first != null && first.keyeq(key);
} }
@Override
public Slot rest() { public Slot rest() {
return next; return next;
} }
@Override
public int arraykey(int max) { public int arraykey(int max) {
// Integer keys can never be weak. // Integer keys can never be weak.
return 0; return 0;
} }
@Override
public Slot set(StrongSlot target, LuaValue value) { public Slot set(StrongSlot target, LuaValue value) {
LuaValue key = strongkey(); LuaValue key = strongkey();
if (key != null && target.find(key) != null) { if (key != null && target.find(key) != null) {
@@ -159,8 +170,9 @@ public class WeakTable implements Metatable {
} }
} }
@Override
public Slot add(Slot entry) { public Slot add(Slot entry) {
next = (next != null)? next.add(entry): entry; next = next != null? next.add(entry): entry;
if (strongkey() != null && strongvalue() != null) { if (strongkey() != null && strongvalue() != null) {
return this; return this;
} else { } else {
@@ -168,6 +180,7 @@ public class WeakTable implements Metatable {
} }
} }
@Override
public Slot remove(StrongSlot target) { public Slot remove(StrongSlot target) {
LuaValue key = strongkey(); LuaValue key = strongkey();
if (key == null) { if (key == null) {
@@ -181,6 +194,7 @@ public class WeakTable implements Metatable {
} }
} }
@Override
public Slot relink(Slot rest) { public Slot relink(Slot rest) {
if (strongkey() != null && strongvalue() != null) { if (strongkey() != null && strongvalue() != null) {
if (rest == null && this.next == null) { if (rest == null && this.next == null) {
@@ -218,19 +232,23 @@ public class WeakTable implements Metatable {
this.keyhash = copyFrom.keyhash; this.keyhash = copyFrom.keyhash;
} }
@Override
public int keyindex(int mask) { public int keyindex(int mask) {
return LuaTable.hashmod(keyhash, mask); return LuaTable.hashmod(keyhash, mask);
} }
@Override
public Slot set(LuaValue value) { public Slot set(LuaValue value) {
this.value = value; this.value = value;
return this; return this;
} }
@Override
public LuaValue strongkey() { public LuaValue strongkey() {
return strengthen(key); return strengthen(key);
} }
@Override
protected WeakSlot copy(Slot rest) { protected WeakSlot copy(Slot rest) {
return new WeakKeySlot(this, rest); return new WeakKeySlot(this, rest);
} }
@@ -246,19 +264,23 @@ public class WeakTable implements Metatable {
super(copyFrom.key, copyFrom.value, next); super(copyFrom.key, copyFrom.value, next);
} }
@Override
public int keyindex(int mask) { public int keyindex(int mask) {
return LuaTable.hashSlot(strongkey(), mask); return LuaTable.hashSlot(strongkey(), mask);
} }
@Override
public Slot set(LuaValue value) { public Slot set(LuaValue value) {
this.value = weaken(value); this.value = weaken(value);
return this; return this;
} }
@Override
public LuaValue strongvalue() { public LuaValue strongvalue() {
return strengthen(value); return strengthen(value);
} }
@Override
protected WeakSlot copy(Slot next) { protected WeakSlot copy(Slot next) {
return new WeakValueSlot(this, next); return new WeakValueSlot(this, next);
} }
@@ -278,23 +300,28 @@ public class WeakTable implements Metatable {
keyhash = copyFrom.keyhash; keyhash = copyFrom.keyhash;
} }
@Override
public int keyindex(int hashMask) { public int keyindex(int hashMask) {
return LuaTable.hashmod(keyhash, hashMask); return LuaTable.hashmod(keyhash, hashMask);
} }
@Override
public Slot set(LuaValue value) { public Slot set(LuaValue value) {
this.value = weaken(value); this.value = weaken(value);
return this; return this;
} }
@Override
public LuaValue strongkey() { public LuaValue strongkey() {
return strengthen(key); return strengthen(key);
} }
@Override
public LuaValue strongvalue() { public LuaValue strongvalue() {
return strengthen(value); return strengthen(value);
} }
@Override
protected WeakSlot copy(Slot next) { protected WeakSlot copy(Slot next) {
return new WeakKeyAndValueSlot(this, 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 * Self-sent message to convert a value to its weak counterpart
* *
* @param value value to convert * @param value value to convert
* @return {@link LuaValue} that is a strong or weak reference, depending on * @return {@link LuaValue} that is a strong or weak reference, depending on
* type of {@code value} * type of {@code value}
@@ -322,7 +349,7 @@ public class WeakTable implements Metatable {
/** /**
* Unwrap a LuaValue from a WeakReference and/or WeakUserdata. * Unwrap a LuaValue from a WeakReference and/or WeakUserdata.
* *
* @param ref reference to convert * @param ref reference to convert
* @return LuaValue or null * @return LuaValue or null
* @see #weaken(LuaValue) * @see #weaken(LuaValue)
@@ -339,7 +366,7 @@ public class WeakTable implements Metatable {
/** /**
* Internal class to implement weak values. * Internal class to implement weak values.
* *
* @see WeakTable * @see WeakTable
*/ */
static class WeakValue extends LuaValue { static class WeakValue extends LuaValue {
@@ -349,25 +376,30 @@ public class WeakTable implements Metatable {
ref = new WeakReference(value); ref = new WeakReference(value);
} }
@Override
public int type() { public int type() {
illegal("type", "weak value"); illegal("type", "weak value");
return 0; return 0;
} }
@Override
public String typename() { public String typename() {
illegal("typename", "weak value"); illegal("typename", "weak value");
return null; return null;
} }
@Override
public String toString() { public String toString() {
return "weak<" + ref.get() + ">"; return "weak<" + ref.get() + ">";
} }
@Override
public LuaValue strongvalue() { public LuaValue strongvalue() {
Object o = ref.get(); Object o = ref.get();
return (LuaValue) o; return (LuaValue) o;
} }
@Override
public boolean raweq(LuaValue rhs) { public boolean raweq(LuaValue rhs) {
Object o = ref.get(); Object o = ref.get();
return o != null && rhs.raweq((LuaValue) o); return o != null && rhs.raweq((LuaValue) o);
@@ -376,7 +408,7 @@ public class WeakTable implements Metatable {
/** /**
* Internal class to implement weak userdata values. * Internal class to implement weak userdata values.
* *
* @see WeakTable * @see WeakTable
*/ */
static final class WeakUserdata extends WeakValue { static final class WeakUserdata extends WeakValue {
@@ -389,6 +421,7 @@ public class WeakTable implements Metatable {
mt = value.getmetatable(); mt = value.getmetatable();
} }
@Override
public LuaValue strongvalue() { public LuaValue strongvalue() {
Object u = ref.get(); Object u = ref.get();
if (u != null) if (u != null)
@@ -404,10 +437,12 @@ public class WeakTable implements Metatable {
} }
} }
@Override
public LuaValue wrap(LuaValue value) { public LuaValue wrap(LuaValue value) {
return weakvalues? weaken(value): value; return weakvalues? weaken(value): value;
} }
@Override
public LuaValue arrayget(LuaValue[] array, int index) { public LuaValue arrayget(LuaValue[] array, int index) {
LuaValue value = array[index]; LuaValue value = array[index];
if (value != null) { if (value != null) {

View File

@@ -10,7 +10,7 @@
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * 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. * Constants used by the LuaC compiler and related classes.
* *
* @see LuaC * @see LuaC
* @see FuncState * @see FuncState
*/ */
@@ -59,27 +59,27 @@ public class Constants extends Lua {
} }
static void SET_OPCODE(InstructionPtr i, int o) { 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) { 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) { 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) { 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) { 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) { 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) { 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) { 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) { 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) { 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 // vector reallocation

View File

@@ -10,7 +10,7 @@
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * 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}. * command line interface tool such as {@link luac}.
* <p> * <p>
* A lua binary file is created via {@link DumpState#dump}: * A lua binary file is created via {@link DumpState#dump}:
* *
* <pre> * <pre>
* { * {
* &#64;code * &#64;code
@@ -51,9 +51,9 @@ import org.luaj.vm2.Prototype;
* byte[] lua_binary_file_bytes = o.toByteArray(); * byte[] lua_binary_file_bytes = o.toByteArray();
* } * }
* </pre> * </pre>
* *
* The {@link LoadState} may be used directly to undump these bytes: * The {@link LoadState} may be used directly to undump these bytes:
* *
* <pre> * <pre>
* {@code * {@code
* Prototypep = LoadState.instance.undump(new ByteArrayInputStream(lua_binary_file_bytes), "main.lua"); * Prototypep = LoadState.instance.undump(new ByteArrayInputStream(lua_binary_file_bytes), "main.lua");
@@ -61,10 +61,10 @@ import org.luaj.vm2.Prototype;
* c.call(); * c.call();
* } * }
* </pre> * </pre>
* *
* *
* More commonly, the {@link Globals#undumper} may be used to undump them: * More commonly, the {@link Globals#undumper} may be used to undump them:
* *
* <pre> * <pre>
* { * {
* &#64;code * &#64;code
@@ -73,7 +73,7 @@ import org.luaj.vm2.Prototype;
* c.call(); * c.call();
* } * }
* </pre> * </pre>
* *
* @see luac * @see luac
* @see LoadState * @see LoadState
* @see Globals * @see Globals
@@ -131,9 +131,9 @@ public class DumpState {
void dumpInt(int x) throws IOException { void dumpInt(int x) throws IOException {
if (IS_LITTLE_ENDIAN) { if (IS_LITTLE_ENDIAN) {
writer.writeByte(x & 0xff); writer.writeByte(x & 0xff);
writer.writeByte((x>>8) & 0xff); writer.writeByte(x>>8 & 0xff);
writer.writeByte((x>>16) & 0xff); writer.writeByte(x>>16 & 0xff);
writer.writeByte((x>>24) & 0xff); writer.writeByte(x>>24 & 0xff);
} else { } else {
writer.writeInt(x); writer.writeInt(x);
} }
@@ -286,7 +286,7 @@ public class DumpState {
} }
/** /**
* *
* @param f the function to dump * @param f the function to dump
* @param w the output stream to dump to * @param w the output stream to dump to
* @param stripDebug true to strip debugging info, false otherwise * @param stripDebug true to strip debugging info, false otherwise
@@ -312,7 +312,7 @@ public class DumpState {
DumpState D = new DumpState(w, stripDebug); DumpState D = new DumpState(w, stripDebug);
D.IS_LITTLE_ENDIAN = littleendian; D.IS_LITTLE_ENDIAN = littleendian;
D.NUMBER_FORMAT = numberFormat; 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.dumpHeader();
D.dumpFunction(f); D.dumpFunction(f);
return D.status; return D.status;

View File

@@ -10,7 +10,7 @@
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * 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 */ short nactvar; /* # active locals outside the breakable structure */
boolean upval; /* true if some variable in the block is an upvalue */ boolean upval; /* true if some variable in the block is an upvalue */
boolean isloop; /* true if `block' is a loop */ boolean isloop; /* true if `block' is a loop */
}; }
Prototype f; /* current function header */ Prototype f; /* current function header */
Hashtable h; /* table to find (and reuse) elements in `k' */ 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) { void errorlimit(int limit, String what) {
// TODO: report message logic. // 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.L.pushfstring("function at line " + f.linedefined + " has more than " + limit + " " + what);
ls.lexerror(msg, 0); ls.lexerror(msg, 0);
} }
@@ -118,7 +118,7 @@ public class FuncState extends Constants {
} }
void removevars(int tolevel) { void removevars(int tolevel) {
ls.dyd.n_actvar -= (nactvar-tolevel); ls.dyd.n_actvar -= nactvar-tolevel;
while ( nactvar > tolevel ) while ( nactvar > tolevel )
getlocvar(--nactvar).endpc = pc; getlocvar(--nactvar).endpc = pc;
} }
@@ -245,7 +245,7 @@ public class FuncState extends Constants {
} }
boolean hasmultret(int k) { boolean hasmultret(int k) {
return ((k) == LexState.VCALL || (k) == LexState.VVARARG); return k == LexState.VCALL || k == LexState.VVARARG;
} }
void lastlistfield(ConsControl cc) { void lastlistfield(ConsControl cc) {
@@ -276,7 +276,7 @@ public class FuncState extends Constants {
if (GET_OPCODE(previous_code) == OP_LOADNIL) { if (GET_OPCODE(previous_code) == OP_LOADNIL) {
int pfrom = GETARG_A(previous_code); int pfrom = GETARG_A(previous_code);
int pl = pfrom+GETARG_B(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) if (pfrom < from)
from = pfrom; /* from = min(from, pfrom) */ from = pfrom; /* from = min(from, pfrom) */
if (pl > l) if (pl > l)
@@ -334,7 +334,7 @@ public class FuncState extends Constants {
return LexState.NO_JUMP; return LexState.NO_JUMP;
else else
/* turn offset into absolute position */ /* turn offset into absolute position */
return (pc+1)+offset; return pc+1+offset;
} }
InstructionPtr getjumpcontrol(int pc) { InstructionPtr getjumpcontrol(int pc) {
@@ -466,7 +466,7 @@ public class FuncState extends Constants {
return ((Integer) h.get(v)).intValue(); return ((Integer) h.get(v)).intValue();
} }
final int idx = this.nk; final int idx = this.nk;
this.h.put(v, new Integer(idx)); this.h.put(v, Integer.valueOf(idx));
final Prototype f = this.f; final Prototype f = this.f;
if (f.k == null || nk+1 >= f.k.length) if (f.k == null || nk+1 >= f.k.length)
f.k = realloc(f.k, nk*2+1); f.k = realloc(f.k, nk*2+1);
@@ -482,14 +482,14 @@ public class FuncState extends Constants {
if (r instanceof LuaDouble) { if (r instanceof LuaDouble) {
double d = r.todouble(); double d = r.todouble();
int i = (int) d; int i = (int) d;
if (d == (double) i) if (d == i)
r = LuaInteger.valueOf(i); r = LuaInteger.valueOf(i);
} }
return this.addk(r); return this.addk(r);
} }
int boolK(boolean b) { int boolK(boolean b) {
return this.addk((b? LuaValue.TRUE: LuaValue.FALSE)); return this.addk(b? LuaValue.TRUE: LuaValue.FALSE);
} }
int nilK() { int nilK() {
@@ -562,7 +562,7 @@ public class FuncState extends Constants {
} }
case LexState.VFALSE: case LexState.VFALSE:
case LexState.VTRUE: { 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; break;
} }
case LexState.VK: { 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_f = LexState.NO_JUMP; /* position of an eventual LOAD false */
int p_t = LexState.NO_JUMP; /* position of an eventual LOAD true */ 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)) { 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_f = this.code_label(reg, 0, 1);
p_t = this.code_label(reg, 1, 0); p_t = this.code_label(reg, 1, 0);
this.patchtohere(fj); this.patchtohere(fj);
@@ -662,7 +662,7 @@ public class FuncState extends Constants {
case LexState.VFALSE: case LexState.VFALSE:
case LexState.VNIL: { case LexState.VNIL: {
if (this.nk <= MAXINDEXRK) { /* constant fit in RK operand? */ 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; e.k = LexState.VK;
return RKASK(e.u.info); return RKASK(e.u.info);
} else } else
@@ -699,7 +699,7 @@ public class FuncState extends Constants {
break; break;
} }
case LexState.VINDEXED: { 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); int e = this.exp2RK(ex);
this.codeABC(op, var.u.ind_t, var.u.ind_idx, e); this.codeABC(op, var.u.ind_t, var.u.ind_idx, e);
break; break;
@@ -730,7 +730,7 @@ public class FuncState extends Constants {
&& Lua.GET_OPCODE(pc.get()) != OP_TEST); && Lua.GET_OPCODE(pc.get()) != OP_TEST);
// SETARG_A(pc, !(GETARG_A(pc.get()))); // SETARG_A(pc, !(GETARG_A(pc.get())));
int a = 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); SETARG_A(pc, nota);
} }
@@ -739,7 +739,7 @@ public class FuncState extends Constants {
int ie = this.getcode(e); int ie = this.getcode(e);
if (GET_OPCODE(ie) == OP_NOT) { if (GET_OPCODE(ie) == OP_NOT) {
this.pc--; /* remove previous 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 */ /* else go through */
} }
@@ -838,14 +838,14 @@ public class FuncState extends Constants {
} }
static boolean vkisinreg(int k) { 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) { void indexed(expdesc t, expdesc k) {
t.u.ind_t = (short) t.u.info; t.u.ind_t = (short) t.u.info;
t.u.ind_idx = (short) this.exp2RK(k); t.u.ind_idx = (short) this.exp2RK(k);
LuaC._assert(t.k == LexState.VUPVAL || vkisinreg(t.k)); Constants._assert(t.k == LexState.VUPVAL || vkisinreg(t.k));
t.u.ind_vt = (short) ((t.k == LexState.VUPVAL)? LexState.VUPVAL: LexState.VLOCAL); t.u.ind_vt = (short) (t.k == LexState.VUPVAL? LexState.VUPVAL: LexState.VLOCAL);
t.k = LexState.VINDEXED; t.k = LexState.VINDEXED;
} }
@@ -895,10 +895,9 @@ public class FuncState extends Constants {
} }
void codearith(int op, expdesc e1, expdesc e2, int line) { void codearith(int op, expdesc e1, expdesc e2, int line) {
if (constfolding(op, e1, e2)) if (constfolding(op, e1, e2)) {
return; } else {
else { int o2 = op != OP_UNM && op != OP_LEN? this.exp2RK(e2): 0;
int o2 = (op != OP_UNM && op != OP_LEN)? this.exp2RK(e2): 0;
int o1 = this.exp2RK(e1); int o1 = this.exp2RK(e1);
if (o1 > o2) { if (o1 > o2) {
this.freeexp(e1); this.freeexp(e1);
@@ -1068,11 +1067,11 @@ public class FuncState extends Constants {
this.dischargejpc(); /* `pc' will change */ this.dischargejpc(); /* `pc' will change */
/* put new instruction in code array */ /* put new instruction in code array */
if (f.code == null || this.pc+1 > f.code.length) 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; f.code[this.pc] = instruction;
/* save corresponding line information */ /* save corresponding line information */
if (f.lineinfo == null || this.pc+1 > f.lineinfo.length) 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; f.lineinfo[this.pc] = line;
return this.pc++; return this.pc++;
} }
@@ -1108,7 +1107,7 @@ public class FuncState extends Constants {
void setlist(int base, int nelems, int tostore) { void setlist(int base, int nelems, int tostore) {
int c = (nelems-1)/LFIELDS_PER_FLUSH+1; 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); _assert(tostore != 0);
if (c <= MAXARG_C) if (c <= MAXARG_C)
this.codeABC(OP_SETLIST, base, b, 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 * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * 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 * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * 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 * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * 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)"; protected static final String RESERVED_LOCAL_VAR_FOR_INDEX = "(for index)";
// keywords array // 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_GENERATOR, RESERVED_LOCAL_VAR_FOR_INDEX, RESERVED_LOCAL_VAR_FOR_LIMIT,
RESERVED_LOCAL_VAR_FOR_STATE, RESERVED_LOCAL_VAR_FOR_STEP }; RESERVED_LOCAL_VAR_FOR_STATE, RESERVED_LOCAL_VAR_FOR_STEP };
private static final Hashtable RESERVED_LOCAL_VAR_KEYWORDS_TABLE = new Hashtable(); private static final Hashtable RESERVED_LOCAL_VAR_KEYWORDS_TABLE = new Hashtable();
static { static {
for (int i = 0; i < RESERVED_LOCAL_VAR_KEYWORDS.length; i++) for (String element : RESERVED_LOCAL_VAR_KEYWORDS)
RESERVED_LOCAL_VAR_KEYWORDS_TABLE.put(RESERVED_LOCAL_VAR_KEYWORDS[i], Boolean.TRUE); 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 MAX_INT = Integer.MAX_VALUE-2;
private static final int UCHAR_MAX = 255; // TODO, convert to unicode CHAR_MAX? private static final int UCHAR_MAX = 255; // TODO, convert to unicode CHAR_MAX?
private static final int LUAI_MAXCCALLS = 200; 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 ** 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). ** 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 ** grep "ORDER OPR" if you change these enums
@@ -102,7 +102,7 @@ public class LexState extends Constants {
private static class SemInfo { private static class SemInfo {
LuaValue r; LuaValue r;
LuaString ts; LuaString ts;
}; }
private static class Token { private static class Token {
int token; int token;
@@ -113,7 +113,7 @@ public class LexState extends Constants {
this.seminfo.r = other.seminfo.r; this.seminfo.r = other.seminfo.r;
this.seminfo.ts = other.seminfo.ts; this.seminfo.ts = other.seminfo.ts;
} }
}; }
int current; /* current character (charint) */ int current; /* current character (charint) */
int linenumber; /* input line counter */ int linenumber; /* input line counter */
@@ -151,30 +151,30 @@ public class LexState extends Constants {
final static Hashtable RESERVED = new Hashtable(); final static Hashtable RESERVED = new Hashtable();
static { static {
for (int i = 0; i < NUM_RESERVED; i++) { for (int i = 0; i < NUM_RESERVED; i++) {
LuaString ts = (LuaString) LuaValue.valueOf(luaX_tokens[i]); LuaString ts = LuaValue.valueOf(luaX_tokens[i]);
RESERVED.put(ts, new Integer(FIRST_RESERVED+i)); RESERVED.put(ts, Integer.valueOf(FIRST_RESERVED+i));
} }
} }
private boolean isalnum(int c) { 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); // return Character.isLetterOrDigit(c);
} }
private boolean isalpha(int 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) { private boolean isdigit(int c) {
return (c >= '0' && c <= '9'); return c >= '0' && c <= '9';
} }
private boolean isxdigit(int c) { 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) { private boolean isspace(int c) {
return (c >= 0 && c <= ' '); return c >= 0 && c <= ' ';
} }
public LexState(LuaC.CompileState state, InputStream stream) { public LexState(LuaC.CompileState state, InputStream stream) {
@@ -209,8 +209,7 @@ public class LexState extends Constants {
String token2str(int token) { String token2str(int token) {
if (token < FIRST_RESERVED) { if (token < FIRST_RESERVED) {
return iscntrl(token)? L.pushfstring("char(" + ((int) token) + ")") return iscntrl(token)? L.pushfstring("char(" + token + ")"): L.pushfstring(String.valueOf((char) token));
: L.pushfstring(String.valueOf((char) token));
} else { } else {
return luaX_tokens[token-FIRST_RESERVED]; return luaX_tokens[token-FIRST_RESERVED];
} }
@@ -299,7 +298,7 @@ public class LexState extends Constants {
void buffreplace(char from, char to) { void buffreplace(char from, char to) {
int n = nbuff; int n = nbuff;
char[] p = buff; char[] p = buff;
while ( (--n) >= 0 ) while ( --n >= 0 )
if (p[n] == from) if (p[n] == from)
p[n] = to; p[n] = to;
} }
@@ -316,11 +315,7 @@ public class LexState extends Constants {
++s; ++s;
} }
/* Check for "0x" */ /* Check for "0x" */
if (s+2 >= c.length) if (s+2 >= c.length || c[s++] != '0' || c[s] != 'x' && c[s] != 'X')
return LuaValue.ZERO;
if (c[s++] != '0')
return LuaValue.ZERO;
if (c[s] != 'x' && c[s] != 'X')
return LuaValue.ZERO; return LuaValue.ZERO;
++s; ++s;
@@ -328,11 +323,11 @@ public class LexState extends Constants {
double m = 0; double m = 0;
int e = 0; int e = 0;
while ( s < c.length && isxdigit(c[s]) ) 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] == '.') { if (s < c.length && c[s] == '.') {
++s; // skip dot ++s; // skip dot
while ( s < c.length && isxdigit(c[s]) ) { 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 e -= 4; // Each fractional part shifts right by 2^4
} }
} }
@@ -396,7 +391,7 @@ public class LexState extends Constants {
save_and_next(); save_and_next();
count++; count++;
} }
return (current == s)? count: (-count)-1; return current == s? count: (-count)-1;
} }
void read_long_string(SemInfo seminfo, int sep) { void read_long_string(SemInfo seminfo, int sep) {
@@ -407,7 +402,7 @@ public class LexState extends Constants {
for (boolean endloop = false; !endloop;) { for (boolean endloop = false; !endloop;) {
switch (current) { switch (current) {
case EOZ: 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 */ break; /* to avoid warnings */
case '[': { case '[': {
if (skip_sep() == sep) { if (skip_sep() == sep) {
@@ -462,7 +457,7 @@ public class LexState extends Constants {
nextChar(); nextChar();
int c2 = current; int c2 = current;
if (!isxdigit(c1) || !isxdigit(c2)) 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); return (hexvalue(c1)<<4)+hexvalue(c2);
} }
@@ -529,7 +524,7 @@ public class LexState extends Constants {
int i = 0; int i = 0;
c = 0; c = 0;
do { do {
c = 10*c+(current-'0'); c = 10*c+current-'0';
nextChar(); nextChar();
} while ( ++i < 3 && isdigit(current) ); } while ( ++i < 3 && isdigit(current) );
if (c > UCHAR_MAX) if (c > UCHAR_MAX)
@@ -724,11 +719,11 @@ public class LexState extends Constants {
// ============================================================= // =============================================================
static final boolean vkisvar(final int k) { static final boolean vkisvar(final int k) {
return (VLOCAL <= (k) && (k) <= VINDEXED); return VLOCAL <= k && k <= VINDEXED;
} }
static final boolean vkisinreg(final int k) { static final boolean vkisinreg(final int k) {
return ((k) == VNONRELOC || (k) == VLOCAL); return k == VNONRELOC || k == VLOCAL;
} }
static class expdesc { static class expdesc {
@@ -744,9 +739,9 @@ public class LexState extends Constants {
public void setNval(LuaValue r) { _nval = r; } public void setNval(LuaValue r) { _nval = r; }
public LuaValue nval() { public LuaValue nval() {
return (_nval == null? LuaInteger.valueOf(info): _nval); return _nval == null? LuaInteger.valueOf(info): _nval;
} }
}; }
final U u = new U(); final U u = new U();
final IntPtr t = new IntPtr(); /* patch list of `exit when true' */ final IntPtr t = new IntPtr(); /* patch list of `exit when true' */
@@ -760,11 +755,11 @@ public class LexState extends Constants {
} }
boolean hasjumps() { boolean hasjumps() {
return (t.i != f.i); return t.i != f.i;
} }
boolean isnumeral() { 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) { public void setvalue(expdesc other) {
@@ -786,7 +781,7 @@ public class LexState extends Constants {
Vardesc(int idx) { Vardesc(int idx) {
this.idx = (short) idx; this.idx = (short) idx;
} }
}; }
/* description of pending goto statements and label statements */ /* description of pending goto statements and label statements */
static class Labeldesc { static class Labeldesc {
@@ -801,7 +796,7 @@ public class LexState extends Constants {
this.line = line; this.line = line;
this.nactvar = nactvar; this.nactvar = nactvar;
} }
}; }
/* dynamic structures used by the parser */ /* dynamic structures used by the parser */
static class Dyndata { static class Dyndata {
@@ -811,10 +806,10 @@ public class LexState extends Constants {
int n_gt = 0; int n_gt = 0;
Labeldesc[] label; /* list of active labels */ Labeldesc[] label; /* list of active labels */
int n_label = 0; int n_label = 0;
}; }
boolean hasmultret(int k) { 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) { void check_condition(boolean c, String msg) {
if (!(c)) if (!c)
syntaxerror(msg); syntaxerror(msg);
} }
@@ -902,7 +897,7 @@ public class LexState extends Constants {
void new_localvar(LuaString name) { void new_localvar(LuaString name) {
int reg = registerlocalvar(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) 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 = realloc(dyd.actvar, Math.max(1, dyd.n_actvar*2));
dyd.actvar[dyd.n_actvar++] = new Vardesc(reg); 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 nh; /* total number of `record' elements */
int na; /* total number of array elements */ int na; /* total number of array elements */
int tostore; /* number of array elements pending to be stored */ int tostore; /* number of array elements pending to be stored */
}; }
void recfield(ConsControl cc) { void recfield(ConsControl cc) {
/* recfield -> (NAME | `['exp1`]') = exp1 */ /* recfield -> (NAME | `['exp1`]') = exp1 */
@@ -1219,13 +1214,13 @@ public class LexState extends Constants {
static int luaO_int2fb(int x) { static int luaO_int2fb(int x) {
int e = 0; /* expoent */ int e = 0; /* expoent */
while ( x >= 16 ) { while ( x >= 16 ) {
x = (x+1)>>1; x = x+1>>1;
e++; e++;
} }
if (x < 8) if (x < 8)
return x; return x;
else else
return ((e+1)<<3) | (((int) x)-8); return e+1<<3 | x-8;
} }
/* }====================================================================== */ /* }====================================================================== */
@@ -1252,7 +1247,7 @@ public class LexState extends Constants {
default: default:
this.syntaxerror("<name> or " + LUA_QL("...") + " expected"); this.syntaxerror("<name> or " + LUA_QL("...") + " expected");
} }
} while ( (f.is_vararg == 0) && this.testnext(',') ); } while ( f.is_vararg == 0 && this.testnext(',') );
} }
this.adjustlocalvars(nparams); this.adjustlocalvars(nparams);
f.numparams = fs.nactvar; f.numparams = fs.nactvar;
@@ -1359,8 +1354,7 @@ public class LexState extends Constants {
return; return;
} }
default: { default: {
this.syntaxerror("unexpected symbol " + t.token + " (" + ((char) t.token) + ")"); this.syntaxerror("unexpected symbol " + t.token + " (" + (char) t.token + ")");
return;
} }
} }
} }
@@ -1513,7 +1507,7 @@ public class LexState extends Constants {
left = (byte) i; left = (byte) i;
right = (byte) j; right = (byte) j;
} }
}; }
static Priority[] priority = { /* ORDER OPR */ static Priority[] priority = { /* ORDER OPR */
new Priority(6, 6), new Priority(6, 6), new Priority(7, 7), new Priority(7, 7), 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; LHS_assign prev;
/* variable (global, local, upvalue, or indexed) */ /* variable (global, local, upvalue, or indexed) */
expdesc v = new expdesc(); expdesc v = new expdesc();
}; }
/* /*
** check whether, in an assignment to a local variable, the local variable ** 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) { void check_conflict(LHS_assign lh, expdesc v) {
FuncState fs = this.fs; 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; boolean conflict = false;
for (; lh != null; lh = lh.prev) { for (; lh != null; lh = lh.prev) {
if (lh.v.k == VINDEXED) { if (lh.v.k == VINDEXED) {
@@ -1630,7 +1624,7 @@ public class LexState extends Constants {
} }
if (conflict) { if (conflict) {
/* copy upvalue/local value to a temporary (in position 'extra') */ /* 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.codeABC(op, extra, v.u.info, 0);
fs.reserveregs(1); fs.reserveregs(1);
} }

View File

@@ -10,7 +10,7 @@
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * 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. * Compiler for Lua.
* *
* <p> * <p>
* Compiles lua source files into lua bytecode within a {@link Prototype}, loads * Compiles lua source files into lua bytecode within a {@link Prototype}, loads
* lua binary files directly into a {@link Prototype}, and optionaly * lua binary files directly into a {@link Prototype}, and optionaly
* instantiates a {@link LuaClosure} around the result using a user-supplied * instantiates a {@link LuaClosure} around the result using a user-supplied
* environment. * environment.
* *
* <p> * <p>
* Implements the {@link org.luaj.vm2.Globals.Compiler} interface for loading * Implements the {@link org.luaj.vm2.Globals.Compiler} interface for loading
* initialized chunks, which is an interface common to lua bytecode compiling * initialized chunks, which is an interface common to lua bytecode compiling
* and java bytecode compiling. * and java bytecode compiling.
* *
* <p> * <p>
* The {@link LuaC} compiler is installed by default by both the * The {@link LuaC} compiler is installed by default by both the
* {@link org.luaj.vm2.lib.jse.JsePlatform} and * {@link org.luaj.vm2.lib.jse.JsePlatform} and
* {@link org.luaj.vm2.lib.jme.JmePlatform} classes, so in the following * {@link org.luaj.vm2.lib.jme.JmePlatform} classes, so in the following
* example, the default {@link LuaC} compiler will be used: * example, the default {@link LuaC} compiler will be used:
* *
* <pre> * <pre>
* { * {
* &#64;code * &#64;code
@@ -60,15 +60,15 @@ import org.luaj.vm2.lib.BaseLib;
* globals.load(new StringReader("print 'hello'"), "main.lua").call(); * globals.load(new StringReader("print 'hello'"), "main.lua").call();
* } * }
* </pre> * </pre>
* *
* To load the LuaC compiler manually, use the install method: * To load the LuaC compiler manually, use the install method:
* *
* <pre> * <pre>
* {@code * {@code
* LuaC.install(globals); * LuaC.install(globals);
* } * }
* </pre> * </pre>
* *
* @see #install(Globals) * @see #install(Globals)
* @see Globals#compiler * @see Globals#compiler
* @see Globals#loader * @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 * Install the compiler so that LoadState will first try to use it when
* handed bytes that are not already a compiled lua chunk. * handed bytes that are not already a compiled lua chunk.
* *
* @param globals the Globals into which this is to be installed. * @param globals the Globals into which this is to be installed.
*/ */
public static void install(Globals globals) { 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. * Compile lua source into a Prototype.
* *
* @param stream InputStream representing the text source conforming to * @param stream InputStream representing the text source conforming to
* lua source syntax. * lua source syntax.
* @param chunkname String name of the chunk to use. * @param chunkname String name of the chunk to use.
* @return Prototype representing the lua chunk for this source. * @return Prototype representing the lua chunk for this source.
* @throws IOException * @throws IOException
*/ */
@Override
public Prototype compile(InputStream stream, String chunkname) throws IOException { 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 { public LuaFunction load(Prototype prototype, String chunkname, LuaValue env) throws IOException {
return new LuaClosure(prototype, env); 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 * LuaC.compile(InputStream, String) and construct LuaClosure
* directly. * directly.
*/ */
@Deprecated
public LuaValue load(InputStream stream, String chunkname, Globals globals) throws IOException { public LuaValue load(InputStream stream, String chunkname, Globals globals) throws IOException {
return new LuaClosure(compile(stream, chunkname), globals); return new LuaClosure(compile(stream, chunkname), globals);
} }
static class CompileState { static class CompileState {
int nCcalls = 0; int nCcalls = 0;
private Hashtable strings = new Hashtable(); private final Hashtable strings = new Hashtable();
protected CompileState() {} protected CompileState() {}
@@ -135,15 +138,15 @@ public class LuaC extends Constants implements Globals.Compiler, Globals.Loader
FuncState funcstate = new FuncState(); FuncState funcstate = new FuncState();
// lexstate.buff = buff; // lexstate.buff = buff;
lexstate.fs = funcstate; 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 */ /* main func. is always vararg */
funcstate.f = new Prototype(); funcstate.f = new Prototype();
funcstate.f.source = (LuaString) LuaValue.valueOf(name); funcstate.f.source = LuaValue.valueOf(name);
lexstate.mainfunc(funcstate); lexstate.mainfunc(funcstate);
LuaC._assert(funcstate.prev == null); Constants._assert(funcstate.prev == null);
/* all scopes should be correctly finished */ /* all scopes should be correctly finished */
LuaC._assert(lexstate.dyd == null Constants._assert(lexstate.dyd == null
|| (lexstate.dyd.n_actvar == 0 && lexstate.dyd.n_gt == 0 && lexstate.dyd.n_label == 0)); || lexstate.dyd.n_actvar == 0 && lexstate.dyd.n_gt == 0 && lexstate.dyd.n_label == 0);
return funcstate.f; return funcstate.f;
} }

View File

@@ -10,7 +10,7 @@
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * 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 * 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.jse.JsePlatform#standardGlobals()} or
* {@link org.luaj.vm2.lib.jme.JmePlatform#standardGlobals()} * {@link org.luaj.vm2.lib.jme.JmePlatform#standardGlobals()}
* *
* <pre> * <pre>
* { * {
* &#64;code * &#64;code
@@ -62,7 +62,7 @@ import org.luaj.vm2.Varargs;
* For special cases where the smallest possible footprint is desired, a minimal * For special cases where the smallest possible footprint is desired, a minimal
* set of libraries could be loaded directly via {@link Globals#load(LuaValue)} * set of libraries could be loaded directly via {@link Globals#load(LuaValue)}
* using code such as: * using code such as:
* *
* <pre> * <pre>
* { * {
* &#64;code * &#64;code
@@ -71,12 +71,12 @@ import org.luaj.vm2.Varargs;
* globals.get("print").call(LuaValue.valueOf("hello, world")); * globals.get("print").call(LuaValue.valueOf("hello, world"));
* } * }
* </pre> * </pre>
* *
* Doing so will ensure the library is properly initialized and loaded into the * Doing so will ensure the library is properly initialized and loaded into the
* globals table. * globals table.
* <p> * <p>
* This is a direct port of the corresponding library in C. * This is a direct port of the corresponding library in C.
* *
* @see org.luaj.vm2.lib.jse.JseBaseLib * @see org.luaj.vm2.lib.jse.JseBaseLib
* @see ResourceFinder * @see ResourceFinder
* @see Globals#finder * @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 * Perform one-time initialization on the library by adding base functions
* to the supplied environment, and returning it as the return value. * to the supplied environment, and returning it as the return value.
* *
* @param modname the module name supplied if this is loaded via 'require'. * @param modname the module name supplied if this is loaded via 'require'.
* @param env the environment to load into, which must be a Globals * @param env the environment to load into, which must be a Globals
* instance. * instance.
*/ */
@Override
public LuaValue call(LuaValue modname, LuaValue env) { public LuaValue call(LuaValue modname, LuaValue env) {
globals = env.checkglobals(); globals = env.checkglobals();
globals.finder = this; globals.finder = this;
@@ -134,15 +135,17 @@ public class BaseLib extends TwoArgFunction implements ResourceFinder {
/** /**
* ResourceFinder implementation * ResourceFinder implementation
* *
* Tries to open the file as a resource, which can work for JSE and JME. * Tries to open the file as a resource, which can work for JSE and JME.
*/ */
@Override
public InputStream findResource(String filename) { public InputStream findResource(String filename) {
return getClass().getResourceAsStream(filename.startsWith("/")? filename: "/" + filename); return getClass().getResourceAsStream(filename.startsWith("/")? filename: "/" + filename);
} }
// "assert", // ( v [,message] ) -> v, message | ERR // "assert", // ( v [,message] ) -> v, message | ERR
static final class _assert extends VarArgFunction { static final class _assert extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) { public Varargs invoke(Varargs args) {
if (!args.arg1().toboolean()) if (!args.arg1().toboolean())
error(args.narg() > 1? args.optjstring(2, "assertion failed!"): "assertion failed!"); 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 // "collectgarbage", // ( opt [,arg] ) -> value
static final class collectgarbage extends VarArgFunction { static final class collectgarbage extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) { public Varargs invoke(Varargs args) {
String s = args.optjstring(1, "collect"); String s = args.optjstring(1, "collect");
if ("collect".equals(s)) { if ("collect".equals(s)) {
@@ -173,6 +177,7 @@ public class BaseLib extends TwoArgFunction implements ResourceFinder {
// "dofile", // ( filename ) -> result1, ... // "dofile", // ( filename ) -> result1, ...
final class dofile extends VarArgFunction { final class dofile extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) { public Varargs invoke(Varargs args) {
args.argcheck(args.isstring(1) || args.isnil(1), 1, "filename must be string or nil"); args.argcheck(args.isstring(1) || args.isnil(1), 1, "filename must be string or nil");
String filename = args.isstring(1)? args.tojstring(1): null; String filename = args.isstring(1)? args.tojstring(1): null;
@@ -184,6 +189,7 @@ public class BaseLib extends TwoArgFunction implements ResourceFinder {
// "error", // ( message [,level] ) -> ERR // "error", // ( message [,level] ) -> ERR
static final class error extends TwoArgFunction { static final class error extends TwoArgFunction {
@Override
public LuaValue call(LuaValue arg1, LuaValue arg2) { public LuaValue call(LuaValue arg1, LuaValue arg2) {
if (arg1.isnil()) if (arg1.isnil())
throw new LuaError(NIL); throw new LuaError(NIL);
@@ -195,10 +201,12 @@ public class BaseLib extends TwoArgFunction implements ResourceFinder {
// "getmetatable", // ( object ) -> table // "getmetatable", // ( object ) -> table
static final class getmetatable extends LibFunction { static final class getmetatable extends LibFunction {
@Override
public LuaValue call() { public LuaValue call() {
return argerror(1, "value expected"); return argerror(1, "value expected");
} }
@Override
public LuaValue call(LuaValue arg) { public LuaValue call(LuaValue arg) {
LuaValue mt = arg.getmetatable(); LuaValue mt = arg.getmetatable();
return mt != null? mt.rawget(METATABLE).optvalue(mt): NIL; 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 // "load", // ( ld [, source [, mode [, env]]] ) -> chunk | nil, msg
final class load extends VarArgFunction { final class load extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) { public Varargs invoke(Varargs args) {
LuaValue ld = args.arg1(); LuaValue ld = args.arg1();
if (!ld.isstring() && !ld.isfunction()) { if (!ld.isstring() && !ld.isfunction()) {
@@ -223,6 +232,7 @@ public class BaseLib extends TwoArgFunction implements ResourceFinder {
// "loadfile", // ( [filename [, mode [, env]]] ) -> chunk | nil, msg // "loadfile", // ( [filename [, mode [, env]]] ) -> chunk | nil, msg
final class loadfile extends VarArgFunction { final class loadfile extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) { public Varargs invoke(Varargs args) {
args.argcheck(args.isstring(1) || args.isnil(1), 1, "filename must be string or nil"); args.argcheck(args.isstring(1) || args.isnil(1), 1, "filename must be string or nil");
String filename = args.isstring(1)? args.tojstring(1): null; 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, ... // "pcall", // (f, arg1, ...) -> status, result1, ...
final class pcall extends VarArgFunction { final class pcall extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) { public Varargs invoke(Varargs args) {
LuaValue func = args.checkvalue(1); LuaValue func = args.checkvalue(1);
if (globals != null && globals.debuglib != null) if (globals != null && globals.debuglib != null)
@@ -261,6 +272,7 @@ public class BaseLib extends TwoArgFunction implements ResourceFinder {
this.baselib = baselib; this.baselib = baselib;
} }
@Override
public Varargs invoke(Varargs args) { public Varargs invoke(Varargs args) {
LuaValue tostring = globals.get("tostring"); LuaValue tostring = globals.get("tostring");
for (int i = 1, n = args.narg(); i <= n; i++) { 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 // "rawequal", // (v1, v2) -> boolean
static final class rawequal extends LibFunction { static final class rawequal extends LibFunction {
@Override
public LuaValue call() { public LuaValue call() {
return argerror(1, "value expected"); return argerror(1, "value expected");
} }
@Override
public LuaValue call(LuaValue arg) { public LuaValue call(LuaValue arg) {
return argerror(2, "value expected"); return argerror(2, "value expected");
} }
@Override
public LuaValue call(LuaValue arg1, LuaValue arg2) { public LuaValue call(LuaValue arg1, LuaValue arg2) {
return valueOf(arg1.raweq(arg2)); return valueOf(arg1.raweq(arg2));
} }
@@ -291,10 +306,12 @@ public class BaseLib extends TwoArgFunction implements ResourceFinder {
// "rawget", // (table, index) -> value // "rawget", // (table, index) -> value
static final class rawget extends TableLibFunction { static final class rawget extends TableLibFunction {
@Override
public LuaValue call(LuaValue arg) { public LuaValue call(LuaValue arg) {
return argerror(2, "value expected"); return argerror(2, "value expected");
} }
@Override
public LuaValue call(LuaValue arg1, LuaValue arg2) { public LuaValue call(LuaValue arg1, LuaValue arg2) {
return arg1.checktable().rawget(arg2); return arg1.checktable().rawget(arg2);
} }
@@ -302,6 +319,7 @@ public class BaseLib extends TwoArgFunction implements ResourceFinder {
// "rawlen", // (v) -> value // "rawlen", // (v) -> value
static final class rawlen extends LibFunction { static final class rawlen extends LibFunction {
@Override
public LuaValue call(LuaValue arg) { public LuaValue call(LuaValue arg) {
return valueOf(arg.rawlen()); return valueOf(arg.rawlen());
} }
@@ -309,14 +327,17 @@ public class BaseLib extends TwoArgFunction implements ResourceFinder {
// "rawset", // (table, index, value) -> table // "rawset", // (table, index, value) -> table
static final class rawset extends TableLibFunction { static final class rawset extends TableLibFunction {
@Override
public LuaValue call(LuaValue table) { public LuaValue call(LuaValue table) {
return argerror(2, "value expected"); return argerror(2, "value expected");
} }
@Override
public LuaValue call(LuaValue table, LuaValue index) { public LuaValue call(LuaValue table, LuaValue index) {
return argerror(3, "value expected"); return argerror(3, "value expected");
} }
@Override
public LuaValue call(LuaValue table, LuaValue index, LuaValue value) { public LuaValue call(LuaValue table, LuaValue index, LuaValue value) {
LuaTable t = table.checktable(); LuaTable t = table.checktable();
if (!index.isvalidkey()) if (!index.isvalidkey())
@@ -328,6 +349,7 @@ public class BaseLib extends TwoArgFunction implements ResourceFinder {
// "select", // (f, ...) -> value1, ... // "select", // (f, ...) -> value1, ...
static final class select extends VarArgFunction { static final class select extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) { public Varargs invoke(Varargs args) {
int n = args.narg()-1; int n = args.narg()-1;
if (args.arg1().equals(valueOf("#"))) if (args.arg1().equals(valueOf("#")))
@@ -341,10 +363,12 @@ public class BaseLib extends TwoArgFunction implements ResourceFinder {
// "setmetatable", // (table, metatable) -> table // "setmetatable", // (table, metatable) -> table
static final class setmetatable extends TableLibFunction { static final class setmetatable extends TableLibFunction {
@Override
public LuaValue call(LuaValue table) { public LuaValue call(LuaValue table) {
return argerror(2, "nil or table expected"); return argerror(2, "nil or table expected");
} }
@Override
public LuaValue call(LuaValue table, LuaValue metatable) { public LuaValue call(LuaValue table, LuaValue metatable) {
final LuaValue mt0 = table.checktable().getmetatable(); final LuaValue mt0 = table.checktable().getmetatable();
if (mt0 != null && !mt0.rawget(METATABLE).isnil()) if (mt0 != null && !mt0.rawget(METATABLE).isnil())
@@ -355,10 +379,12 @@ public class BaseLib extends TwoArgFunction implements ResourceFinder {
// "tonumber", // (e [,base]) -> value // "tonumber", // (e [,base]) -> value
static final class tonumber extends LibFunction { static final class tonumber extends LibFunction {
@Override
public LuaValue call(LuaValue e) { public LuaValue call(LuaValue e) {
return e.tonumber(); return e.tonumber();
} }
@Override
public LuaValue call(LuaValue e, LuaValue base) { public LuaValue call(LuaValue e, LuaValue base) {
if (base.isnil()) if (base.isnil())
return e.tonumber(); return e.tonumber();
@@ -371,6 +397,7 @@ public class BaseLib extends TwoArgFunction implements ResourceFinder {
// "tostring", // (e) -> value // "tostring", // (e) -> value
static final class tostring extends LibFunction { static final class tostring extends LibFunction {
@Override
public LuaValue call(LuaValue arg) { public LuaValue call(LuaValue arg) {
LuaValue h = arg.metatag(TOSTRING); LuaValue h = arg.metatag(TOSTRING);
if (!h.isnil()) if (!h.isnil())
@@ -384,6 +411,7 @@ public class BaseLib extends TwoArgFunction implements ResourceFinder {
// "type", // (v) -> value // "type", // (v) -> value
static final class type extends LibFunction { static final class type extends LibFunction {
@Override
public LuaValue call(LuaValue arg) { public LuaValue call(LuaValue arg) {
return valueOf(arg.typename()); return valueOf(arg.typename());
} }
@@ -391,6 +419,7 @@ public class BaseLib extends TwoArgFunction implements ResourceFinder {
// "xpcall", // (f, err) -> result1, ... // "xpcall", // (f, err) -> result1, ...
final class xpcall extends VarArgFunction { final class xpcall extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) { public Varargs invoke(Varargs args) {
final LuaThread t = globals.running; final LuaThread t = globals.running;
final LuaValue preverror = t.errorfunc; final LuaValue preverror = t.errorfunc;
@@ -424,6 +453,7 @@ public class BaseLib extends TwoArgFunction implements ResourceFinder {
this.next = next; this.next = next;
} }
@Override
public Varargs invoke(Varargs args) { public Varargs invoke(Varargs args) {
return varargsOf(next, args.checktable(1), NIL); return varargsOf(next, args.checktable(1), NIL);
} }
@@ -433,6 +463,7 @@ public class BaseLib extends TwoArgFunction implements ResourceFinder {
static final class ipairs extends VarArgFunction { static final class ipairs extends VarArgFunction {
inext inext = new inext(); inext inext = new inext();
@Override
public Varargs invoke(Varargs args) { public Varargs invoke(Varargs args) {
return varargsOf(inext, args.checktable(1), ZERO); 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 // "next" ( table, [index] ) -> next-index, next-value
static final class next extends VarArgFunction { static final class next extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) { public Varargs invoke(Varargs args) {
return args.checktable(1).next(args.arg(2)); 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 // "inext" ( table, [int-index] ) -> next-index, next-value
static final class inext extends VarArgFunction { static final class inext extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) { public Varargs invoke(Varargs args) {
return args.checktable(1).inext(args.arg(2)); 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 * Load from a named file, returning the chunk or nil,error of can't load
* *
* @param env * @param env
* @param mode * @param mode
* @return Varargs containing chunk, or NIL,error-text on error * @return Varargs containing chunk, or NIL,error-text on error
@@ -493,6 +526,7 @@ public class BaseLib extends TwoArgFunction implements ResourceFinder {
this.func = func; this.func = func;
} }
@Override
public int read() throws IOException { public int read() throws IOException {
if (remaining < 0) if (remaining < 0)
return -1; return -1;

View File

@@ -10,7 +10,7 @@
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * 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 * 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.jse.JsePlatform#standardGlobals()} or
* {@link org.luaj.vm2.lib.jme.JmePlatform#standardGlobals()} * {@link org.luaj.vm2.lib.jme.JmePlatform#standardGlobals()}
* *
* <pre> * <pre>
* { * {
* &#64;code * &#64;code
@@ -43,7 +43,7 @@ import org.luaj.vm2.Varargs;
* <p> * <p>
* To instantiate and use it directly, link it into your globals table via * To instantiate and use it directly, link it into your globals table via
* {@link LuaValue#load(LuaValue)} using code such as: * {@link LuaValue#load(LuaValue)} using code such as:
* *
* <pre> * <pre>
* { * {
* &#64;code * &#64;code
@@ -57,7 +57,7 @@ import org.luaj.vm2.Varargs;
* <p> * <p>
* This has been implemented to match as closely as possible the behavior in the * This has been implemented to match as closely as possible the behavior in the
* corresponding library in C. * corresponding library in C.
* *
* @see LibFunction * @see LibFunction
* @see org.luaj.vm2.lib.jse.JsePlatform * @see org.luaj.vm2.lib.jse.JsePlatform
* @see org.luaj.vm2.lib.jme.JmePlatform * @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 * containing the library functions, adding that table to the supplied
* environment, adding the table to package.loaded, and returning table as * environment, adding the table to package.loaded, and returning table as
* the return value. * the return value.
* *
* @param modname the module name supplied if this is loaded via 'require'. * @param modname the module name supplied if this is loaded via 'require'.
* @param env the environment to load into, which must be a Globals * @param env the environment to load into, which must be a Globals
* instance. * instance.
*/ */
@Override
public LuaValue call(LuaValue modname, LuaValue env) { public LuaValue call(LuaValue modname, LuaValue env) {
LuaTable t = new LuaTable(); LuaTable t = new LuaTable();
bind(t, Bit32LibV.class, new String[] { "band", "bnot", "bor", "btest", "bxor", "extract", "replace" }); 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 { static final class Bit32LibV extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) { public Varargs invoke(Varargs args) {
switch (opcode) { switch (opcode) {
case 0: case 0:
@@ -113,6 +115,7 @@ public class Bit32Lib extends TwoArgFunction {
static final class Bit32Lib2 extends TwoArgFunction { static final class Bit32Lib2 extends TwoArgFunction {
@Override
public LuaValue call(LuaValue arg1, LuaValue arg2) { public LuaValue call(LuaValue arg1, LuaValue arg2) {
switch (opcode) { switch (opcode) {
case 0: case 0:
@@ -200,7 +203,7 @@ public class Bit32Lib extends TwoArgFunction {
return rrotate(x, -disp); return rrotate(x, -disp);
} else { } else {
disp = disp & 31; 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); return lrotate(x, -disp);
} else { } else {
disp = disp & 31; 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) { if (field+width > 32) {
error("trying to access non-existent bits"); 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) { static LuaValue replace(int n, int v, int field, int width) {
@@ -236,12 +239,12 @@ public class Bit32Lib extends TwoArgFunction {
if (field+width > 32) { if (field+width > 32) {
error("trying to access non-existent bits"); error("trying to access non-existent bits");
} }
int mask = (-1>>>(32-width))<<field; int mask = -1>>>32-width<<field;
n = (n & ~mask) | ((v<<field) & mask); n = n & ~mask | v<<field & mask;
return bitsToValue(n); return bitsToValue(n);
} }
private static LuaValue bitsToValue(int x) { 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 * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * 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 * 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.jse.JsePlatform#standardGlobals()} or
* {@link org.luaj.vm2.lib.jme.JmePlatform#standardGlobals()} * {@link org.luaj.vm2.lib.jme.JmePlatform#standardGlobals()}
* *
* <pre> * <pre>
* { * {
* &#64;code * &#64;code
@@ -52,7 +52,7 @@ import org.luaj.vm2.Varargs;
* <p> * <p>
* To instantiate and use it directly, link it into your globals table via * To instantiate and use it directly, link it into your globals table via
* {@link LuaValue#load(LuaValue)} using code such as: * {@link LuaValue#load(LuaValue)} using code such as:
* *
* <pre> * <pre>
* { * {
* &#64;code * &#64;code
@@ -64,7 +64,7 @@ import org.luaj.vm2.Varargs;
* } * }
* </pre> * </pre>
* <p> * <p>
* *
* @see LibFunction * @see LibFunction
* @see org.luaj.vm2.lib.jse.JsePlatform * @see org.luaj.vm2.lib.jse.JsePlatform
* @see org.luaj.vm2.lib.jme.JmePlatform * @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 * containing the library functions, adding that table to the supplied
* environment, adding the table to package.loaded, and returning table as * environment, adding the table to package.loaded, and returning table as
* the return value. * the return value.
* *
* @param modname the module name supplied if this is loaded via 'require'. * @param modname the module name supplied if this is loaded via 'require'.
* @param env the environment to load into, which must be a Globals * @param env the environment to load into, which must be a Globals
* instance. * instance.
*/ */
@Override
public LuaValue call(LuaValue modname, LuaValue env) { public LuaValue call(LuaValue modname, LuaValue env) {
globals = env.checkglobals(); globals = env.checkglobals();
LuaTable coroutine = new LuaTable(); LuaTable coroutine = new LuaTable();
@@ -103,12 +104,14 @@ public class CoroutineLib extends TwoArgFunction {
} }
final class create extends LibFunction { final class create extends LibFunction {
@Override
public LuaValue call(LuaValue f) { public LuaValue call(LuaValue f) {
return new LuaThread(globals, f.checkfunction()); return new LuaThread(globals, f.checkfunction());
} }
} }
static final class resume extends VarArgFunction { static final class resume extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) { public Varargs invoke(Varargs args) {
final LuaThread t = args.checkthread(1); final LuaThread t = args.checkthread(1);
return t.resume(args.subargs(2)); return t.resume(args.subargs(2));
@@ -116,6 +119,7 @@ public class CoroutineLib extends TwoArgFunction {
} }
final class running extends VarArgFunction { final class running extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) { public Varargs invoke(Varargs args) {
final LuaThread r = globals.running; final LuaThread r = globals.running;
return varargsOf(r, valueOf(r.isMainThread())); return varargsOf(r, valueOf(r.isMainThread()));
@@ -123,6 +127,7 @@ public class CoroutineLib extends TwoArgFunction {
} }
static final class status extends LibFunction { static final class status extends LibFunction {
@Override
public LuaValue call(LuaValue t) { public LuaValue call(LuaValue t) {
LuaThread lt = t.checkthread(); LuaThread lt = t.checkthread();
return valueOf(lt.getStatus()); return valueOf(lt.getStatus());
@@ -130,12 +135,14 @@ public class CoroutineLib extends TwoArgFunction {
} }
final class yield extends VarArgFunction { final class yield extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) { public Varargs invoke(Varargs args) {
return globals.yield(args); return globals.yield(args);
} }
} }
final class wrap extends LibFunction { final class wrap extends LibFunction {
@Override
public LuaValue call(LuaValue f) { public LuaValue call(LuaValue f) {
final LuaValue func = f.checkfunction(); final LuaValue func = f.checkfunction();
final LuaThread thread = new LuaThread(globals, func); final LuaThread thread = new LuaThread(globals, func);
@@ -150,6 +157,7 @@ public class CoroutineLib extends TwoArgFunction {
this.luathread = luathread; this.luathread = luathread;
} }
@Override
public Varargs invoke(Varargs args) { public Varargs invoke(Varargs args) {
final Varargs result = luathread.resume(args); final Varargs result = luathread.resume(args);
if (result.arg1().toboolean()) { if (result.arg1().toboolean()) {

View File

@@ -10,7 +10,7 @@
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * 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 * 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.jse.JsePlatform#debugGlobals()} or
* {@link org.luaj.vm2.lib.jme.JmePlatform#debugGlobals()} * {@link org.luaj.vm2.lib.jme.JmePlatform#debugGlobals()}
* *
* <pre> * <pre>
* { * {
* &#64;code * &#64;code
@@ -63,7 +63,7 @@ import org.luaj.vm2.Varargs;
* <p> * <p>
* To instantiate and use it directly, link it into your globals table via * To instantiate and use it directly, link it into your globals table via
* {@link LuaValue#load(LuaValue)} using code such as: * {@link LuaValue#load(LuaValue)} using code such as:
* *
* <pre> * <pre>
* { * {
* &#64;code * &#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 * 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 * and modify all underlying lua values within a Java VM so should not be
* exposed to client code in a shared server environment. * exposed to client code in a shared server environment.
* *
* @see LibFunction * @see LibFunction
* @see org.luaj.vm2.lib.jse.JsePlatform * @see org.luaj.vm2.lib.jse.JsePlatform
* @see org.luaj.vm2.lib.jme.JmePlatform * @see org.luaj.vm2.lib.jme.JmePlatform
@@ -90,11 +90,11 @@ public class DebugLib extends TwoArgFunction {
public static boolean TRACE; public static boolean TRACE;
static { static {
try { try {
CALLS = (null != System.getProperty("CALLS")); CALLS = null != System.getProperty("CALLS");
} catch (Exception e) { } catch (Exception e) {
} }
try { try {
TRACE = (null != System.getProperty("TRACE")); TRACE = null != System.getProperty("TRACE");
} catch (Exception e) { } catch (Exception e) {
} }
} }
@@ -128,11 +128,12 @@ public class DebugLib extends TwoArgFunction {
* containing the library functions, adding that table to the supplied * containing the library functions, adding that table to the supplied
* environment, adding the table to package.loaded, and returning table as * environment, adding the table to package.loaded, and returning table as
* the return value. * the return value.
* *
* @param modname the module name supplied if this is loaded via 'require'. * @param modname the module name supplied if this is loaded via 'require'.
* @param env the environment to load into, which must be a Globals * @param env the environment to load into, which must be a Globals
* instance. * instance.
*/ */
@Override
public LuaValue call(LuaValue modname, LuaValue env) { public LuaValue call(LuaValue modname, LuaValue env) {
globals = env.checkglobals(); globals = env.checkglobals();
globals.debuglib = this; globals.debuglib = this;
@@ -161,6 +162,7 @@ public class DebugLib extends TwoArgFunction {
// debug.debug() // debug.debug()
static final class debug extends ZeroArgFunction { static final class debug extends ZeroArgFunction {
@Override
public LuaValue call() { public LuaValue call() {
return NONE; return NONE;
} }
@@ -168,6 +170,7 @@ public class DebugLib extends TwoArgFunction {
// debug.gethook ([thread]) // debug.gethook ([thread])
final class gethook extends VarArgFunction { final class gethook extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) { public Varargs invoke(Varargs args) {
LuaThread t = args.narg() > 0? args.checkthread(1): globals.running; LuaThread t = args.narg() > 0? args.checkthread(1): globals.running;
LuaThread.State s = t.state; LuaThread.State s = t.state;
@@ -178,6 +181,7 @@ public class DebugLib extends TwoArgFunction {
// debug.getinfo ([thread,] f [, what]) // debug.getinfo ([thread,] f [, what])
final class getinfo extends VarArgFunction { final class getinfo extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) { public Varargs invoke(Varargs args) {
int a = 1; int a = 1;
LuaThread thread = args.isthread(a)? args.checkthread(a++): globals.running; LuaThread thread = args.isthread(a)? args.checkthread(a++): globals.running;
@@ -241,6 +245,7 @@ public class DebugLib extends TwoArgFunction {
// debug.getlocal ([thread,] f, local) // debug.getlocal ([thread,] f, local)
final class getlocal extends VarArgFunction { final class getlocal extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) { public Varargs invoke(Varargs args) {
int a = 1; int a = 1;
LuaThread thread = args.isthread(a)? args.checkthread(a++): globals.running; LuaThread thread = args.isthread(a)? args.checkthread(a++): globals.running;
@@ -253,6 +258,7 @@ public class DebugLib extends TwoArgFunction {
// debug.getmetatable (value) // debug.getmetatable (value)
static final class getmetatable extends LibFunction { static final class getmetatable extends LibFunction {
@Override
public LuaValue call(LuaValue v) { public LuaValue call(LuaValue v) {
LuaValue mt = v.getmetatable(); LuaValue mt = v.getmetatable();
return mt != null? mt: NIL; return mt != null? mt: NIL;
@@ -261,6 +267,7 @@ public class DebugLib extends TwoArgFunction {
// debug.getregistry () // debug.getregistry ()
final class getregistry extends ZeroArgFunction { final class getregistry extends ZeroArgFunction {
@Override
public LuaValue call() { public LuaValue call() {
return globals; return globals;
} }
@@ -268,6 +275,7 @@ public class DebugLib extends TwoArgFunction {
// debug.getupvalue (f, up) // debug.getupvalue (f, up)
static final class getupvalue extends VarArgFunction { static final class getupvalue extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) { public Varargs invoke(Varargs args) {
LuaValue func = args.checkfunction(1); LuaValue func = args.checkfunction(1);
int up = args.checkint(2); int up = args.checkint(2);
@@ -284,6 +292,7 @@ public class DebugLib extends TwoArgFunction {
// debug.getuservalue (u) // debug.getuservalue (u)
static final class getuservalue extends LibFunction { static final class getuservalue extends LibFunction {
@Override
public LuaValue call(LuaValue u) { public LuaValue call(LuaValue u) {
return u.isuserdata()? u: NIL; return u.isuserdata()? u: NIL;
} }
@@ -291,6 +300,7 @@ public class DebugLib extends TwoArgFunction {
// debug.sethook ([thread,] hook, mask [, count]) // debug.sethook ([thread,] hook, mask [, count])
final class sethook extends VarArgFunction { final class sethook extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) { public Varargs invoke(Varargs args) {
int a = 1; int a = 1;
LuaThread t = args.isthread(a)? args.checkthread(a++): globals.running; 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) // debug.setlocal ([thread,] level, local, value)
final class setlocal extends VarArgFunction { final class setlocal extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) { public Varargs invoke(Varargs args) {
int a = 1; int a = 1;
LuaThread thread = args.isthread(a)? args.checkthread(a++): globals.running; LuaThread thread = args.isthread(a)? args.checkthread(a++): globals.running;
@@ -335,6 +346,7 @@ public class DebugLib extends TwoArgFunction {
// debug.setmetatable (value, table) // debug.setmetatable (value, table)
static final class setmetatable extends TwoArgFunction { static final class setmetatable extends TwoArgFunction {
@Override
public LuaValue call(LuaValue value, LuaValue table) { public LuaValue call(LuaValue value, LuaValue table) {
LuaValue mt = table.opttable(null); LuaValue mt = table.opttable(null);
switch (value.type()) { switch (value.type()) {
@@ -365,6 +377,7 @@ public class DebugLib extends TwoArgFunction {
// debug.setupvalue (f, up, value) // debug.setupvalue (f, up, value)
static final class setupvalue extends VarArgFunction { static final class setupvalue extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) { public Varargs invoke(Varargs args) {
LuaValue func = args.checkfunction(1); LuaValue func = args.checkfunction(1);
int up = args.checkint(2); int up = args.checkint(2);
@@ -383,6 +396,7 @@ public class DebugLib extends TwoArgFunction {
// debug.setuservalue (udata, value) // debug.setuservalue (udata, value)
static final class setuservalue extends VarArgFunction { static final class setuservalue extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) { public Varargs invoke(Varargs args) {
Object o = args.checkuserdata(1); Object o = args.checkuserdata(1);
LuaValue v = args.checkvalue(2); LuaValue v = args.checkvalue(2);
@@ -395,6 +409,7 @@ public class DebugLib extends TwoArgFunction {
// debug.traceback ([thread,] [message [, level]]) // debug.traceback ([thread,] [message [, level]])
final class traceback extends VarArgFunction { final class traceback extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) { public Varargs invoke(Varargs args) {
int a = 1; int a = 1;
LuaThread thread = args.isthread(a)? args.checkthread(a++): globals.running; LuaThread thread = args.isthread(a)? args.checkthread(a++): globals.running;
@@ -407,6 +422,7 @@ public class DebugLib extends TwoArgFunction {
// debug.upvalueid (f, n) // debug.upvalueid (f, n)
static final class upvalueid extends VarArgFunction { static final class upvalueid extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) { public Varargs invoke(Varargs args) {
LuaValue func = args.checkfunction(1); LuaValue func = args.checkfunction(1);
int up = args.checkint(2); int up = args.checkint(2);
@@ -422,6 +438,7 @@ public class DebugLib extends TwoArgFunction {
// debug.upvaluejoin (f1, n1, f2, n2) // debug.upvaluejoin (f1, n1, f2, n2)
static final class upvaluejoin extends VarArgFunction { static final class upvaluejoin extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) { public Varargs invoke(Varargs args) {
LuaClosure f1 = args.checkclosure(1); LuaClosure f1 = args.checkclosure(1);
int n1 = args.checkint(2); int n1 = args.checkint(2);
@@ -536,7 +553,7 @@ public class DebugLib extends TwoArgFunction {
this.source = p.source != null? p.source.tojstring(): "=?"; this.source = p.source != null? p.source.tojstring(): "=?";
this.linedefined = p.linedefined; this.linedefined = p.linedefined;
this.lastlinedefined = p.lastlinedefined; this.lastlinedefined = p.lastlinedefined;
this.what = (this.linedefined == 0)? "main": "Lua"; this.what = this.linedefined == 0? "main": "Lua";
this.short_src = p.shortsource(); this.short_src = p.shortsource();
} else { } else {
this.source = "=[Java]"; this.source = "=[Java]";
@@ -593,7 +610,7 @@ public class DebugLib extends TwoArgFunction {
/** /**
* Get the traceback starting at a specific level. * Get the traceback starting at a specific level.
* *
* @param level * @param level
* @return String containing the traceback. * @return String containing the traceback.
*/ */
@@ -886,9 +903,9 @@ public class DebugLib extends TwoArgFunction {
case Lua.OP_GETTABLE: { case Lua.OP_GETTABLE: {
int k = Lua.GETARG_C(i); /* key index */ int k = Lua.GETARG_C(i); /* key index */
int t = Lua.GETARG_B(i); /* table 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) ? 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); String jname = kname(p, pc, k);
return new NameWhat(jname, vn != null && vn.eq_b(ENV)? "global": "field"); 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_LOADK:
case Lua.OP_LOADKX: { 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()) { if (p.k[b].isstring()) {
name = p.k[b].strvalue(); name = p.k[b].strvalue();
return new NameWhat(name.tojstring(), "constant"); return new NameWhat(name.tojstring(), "constant");
@@ -976,7 +993,7 @@ public class DebugLib extends TwoArgFunction {
break; break;
} }
case Lua.OP_SETLIST: { // Lua.testAMode(Lua.OP_SETLIST) == false 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 pc++; // if c == 0 then c stored in next op -> skip
break; break;
} }

View File

@@ -10,7 +10,7 @@
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * 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 * 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.jse.JsePlatform#standardGlobals()} or
* {@link org.luaj.vm2.lib.jme.JmePlatform#standardGlobals()} * {@link org.luaj.vm2.lib.jme.JmePlatform#standardGlobals()}
* *
* <pre> * <pre>
* { * {
* &#64;code * &#64;code
@@ -55,7 +55,7 @@ import org.luaj.vm2.Varargs;
* globals.get("io").get("write").call(LuaValue.valueOf("hello, world\n")); * globals.get("io").get("write").call(LuaValue.valueOf("hello, world\n"));
* } * }
* </pre> * </pre>
* *
* In this example the platform-specific {@link org.luaj.vm2.lib.jse.JseIoLib} * 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 * 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 * this class, whereas the {@link org.luaj.vm2.lib.jse.JsePlatform} would load
@@ -63,7 +63,7 @@ import org.luaj.vm2.Varargs;
* <p> * <p>
* To instantiate and use it directly, link it into your globals table via * To instantiate and use it directly, link it into your globals table via
* {@link LuaValue#load(LuaValue)} using code such as: * {@link LuaValue#load(LuaValue)} using code such as:
* *
* <pre> * <pre>
* { * {
* &#64;code * &#64;code
@@ -77,7 +77,7 @@ import org.luaj.vm2.Varargs;
* <p> * <p>
* This has been implemented to match as closely as possible the behavior in the * This has been implemented to match as closely as possible the behavior in the
* corresponding library in C. * corresponding library in C.
* *
* @see LibFunction * @see LibFunction
* @see org.luaj.vm2.lib.jse.JsePlatform * @see org.luaj.vm2.lib.jse.JsePlatform
* @see org.luaj.vm2.lib.jme.JmePlatform * @see org.luaj.vm2.lib.jme.JmePlatform
@@ -86,35 +86,35 @@ import org.luaj.vm2.Varargs;
* @see <a href= * @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> * "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 { protected abstract class File extends LuaValue {
abstract public void write(LuaString string) throws IOException; 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 // 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 // get length remaining to read
abstract public int remaining() throws IOException; public abstract int remaining() throws IOException;
// peek ahead one character // 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 // 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 // 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 { public boolean eof() throws IOException {
try { try {
@@ -125,24 +125,29 @@ abstract public class IoLib extends TwoArgFunction {
} }
// delegate method access to file methods table // delegate method access to file methods table
@Override
public LuaValue get(LuaValue key) { public LuaValue get(LuaValue key) {
return filemethods.get(key); return filemethods.get(key);
} }
// essentially a userdata instance // essentially a userdata instance
@Override
public int type() { public int type() {
return LuaValue.TUSERDATA; return LuaValue.TUSERDATA;
} }
@Override
public String typename() { public String typename() {
return "userdata"; return "userdata";
} }
// displays as "file" type // displays as "file" type
@Override
public String tojstring() { public String tojstring() {
return "file: " + Integer.toHexString(hashCode()); return "file: " + Integer.toHexString(hashCode());
} }
@Override
public void finalize() { public void finalize() {
if (!isclosed()) { if (!isclosed()) {
try { try {
@@ -164,7 +169,7 @@ abstract public class IoLib extends TwoArgFunction {
/** /**
* Wrap the standard input. * Wrap the standard input.
* *
* @return File * @return File
* @throws IOException * @throws IOException
*/ */
@@ -172,7 +177,7 @@ abstract public class IoLib extends TwoArgFunction {
/** /**
* Wrap the standard output. * Wrap the standard output.
* *
* @return File * @return File
* @throws IOException * @throws IOException
*/ */
@@ -180,7 +185,7 @@ abstract public class IoLib extends TwoArgFunction {
/** /**
* Wrap the standard error output. * Wrap the standard error output.
* *
* @return File * @return File
* @throws IOException * @throws IOException
*/ */
@@ -188,7 +193,7 @@ abstract public class IoLib extends TwoArgFunction {
/** /**
* Open a file in a particular mode. * Open a file in a particular mode.
* *
* @param filename * @param filename
* @param readMode true if opening in read mode * @param readMode true if opening in read mode
* @param appendMode true if opening in append mode * @param appendMode true if opening in append mode
@@ -202,7 +207,7 @@ abstract public class IoLib extends TwoArgFunction {
/** /**
* Open a temporary file. * Open a temporary file.
* *
* @return File object if successful * @return File object if successful
* @throws IOException if could not be opened * @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 * Start a new process and return a file for input or output
* *
* @param prog the program to execute * @param prog the program to execute
* @param mode "r" to read, "w" to write * @param mode "r" to read, "w" to write
* @return File to read to or write from * @return File to read to or write from
@@ -260,6 +265,7 @@ abstract public class IoLib extends TwoArgFunction {
protected Globals globals; protected Globals globals;
@Override
public LuaValue call(LuaValue modname, LuaValue env) { public LuaValue call(LuaValue modname, LuaValue env) {
globals = env.checkglobals(); globals = env.checkglobals();
@@ -310,13 +316,13 @@ abstract public class IoLib extends TwoArgFunction {
} }
public IoLibV(File f, String name, int opcode, IoLib iolib) { public IoLibV(File f, String name, int opcode, IoLib iolib) {
super();
this.f = f; this.f = f;
this.name = name; this.name = name;
this.opcode = opcode; this.opcode = opcode;
this.iolib = iolib; this.iolib = iolib;
} }
@Override
public Varargs invoke(Varargs args) { public Varargs invoke(Varargs args) {
try { try {
switch (opcode) { switch (opcode) {
@@ -630,9 +636,7 @@ abstract public class IoLib extends TwoArgFunction {
int len = mode.length(); int len = mode.length();
for (int i = 0; i < len; i++) { // [rwa][+]?b* for (int i = 0; i < len; i++) { // [rwa][+]?b*
char ch = mode.charAt(i); char ch = mode.charAt(i);
if (i == 0 && "rwa".indexOf(ch) >= 0) if ((i == 0 && "rwa".indexOf(ch) >= 0) || (i == 1 && ch == '+'))
continue;
if (i == 1 && ch == '+')
continue; continue;
if (i >= 1 && ch == 'b') if (i >= 1 && ch == 'b')
continue; continue;

View File

@@ -10,7 +10,7 @@
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -57,12 +57,12 @@ import org.luaj.vm2.Varargs;
* <p> * <p>
* For example, the following code will implement a library called "hyperbolic" * For example, the following code will implement a library called "hyperbolic"
* with two functions, "sinh", and "cosh": * with two functions, "sinh", and "cosh":
* *
* <pre> * <pre>
* {@code * {@code
* import org.luaj.vm2.LuaValue; * import org.luaj.vm2.LuaValue;
* import org.luaj.vm2.lib.*; * import org.luaj.vm2.lib.*;
* *
* public class hyperbolic extends TwoArgFunction { * public class hyperbolic extends TwoArgFunction {
* *
* public hyperbolic() {} * public hyperbolic() {}
@@ -80,7 +80,7 @@ import org.luaj.vm2.Varargs;
* return LuaValue.valueOf(Math.sinh(x.checkdouble())); * return LuaValue.valueOf(Math.sinh(x.checkdouble()));
* } * }
* } * }
* *
* static class cosh extends OneArgFunction { * static class cosh extends OneArgFunction {
* public LuaValue call(LuaValue x) { * public LuaValue call(LuaValue x) {
* return LuaValue.valueOf(Math.cosh(x.checkdouble())); * return LuaValue.valueOf(Math.cosh(x.checkdouble()));
@@ -89,7 +89,7 @@ import org.luaj.vm2.Varargs;
*} *}
*} *}
* </pre> * </pre>
* *
* The default constructor is used to instantiate the library in response to * The default constructor is used to instantiate the library in response to
* {@code require 'hyperbolic'} statement, provided it is on Java&quot;s class * {@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 * path. This instance is then invoked with 2 arguments: the name supplied to
@@ -100,7 +100,7 @@ import org.luaj.vm2.Varargs;
* 'env' argument. * 'env' argument.
* <p> * <p>
* To test it, a script such as this can be used: * To test it, a script such as this can be used:
* *
* <pre> * <pre>
* {@code * {@code
* local t = require('hyperbolic') * local t = require('hyperbolic')
@@ -115,7 +115,7 @@ import org.luaj.vm2.Varargs;
* </pre> * </pre>
* <p> * <p>
* It should produce something like: * It should produce something like:
* *
* <pre> * <pre>
* {@code * {@code
* t table: 3dbbd23f * t table: 3dbbd23f
@@ -152,6 +152,7 @@ abstract public class LibFunction extends LuaFunction {
protected LibFunction() { protected LibFunction() {
} }
@Override
public String tojstring() { public String tojstring() {
return name != null? "function: " + name: super.tojstring(); return name != null? "function: " + name: super.tojstring();
} }
@@ -161,7 +162,7 @@ abstract public class LibFunction extends LuaFunction {
* <p> * <p>
* An array of names is provided, and the first name is bound with opcode = * An array of names is provided, and the first name is bound with opcode =
* 0, second with 1, etc. * 0, second with 1, etc.
* *
* @param env The environment to apply to each bound function * @param env The environment to apply to each bound function
* @param factory the Class to instantiate for each bound function * @param factory the Class to instantiate for each bound function
* @param names array of String names, one for each function. * @param names array of String names, one for each function.
@@ -176,7 +177,7 @@ abstract public class LibFunction extends LuaFunction {
* <p> * <p>
* An array of names is provided, and the first name is bound with opcode = * An array of names is provided, and the first name is bound with opcode =
* {@code firstopcode}, second with {@code firstopcode+1}, etc. * {@code firstopcode}, second with {@code firstopcode+1}, etc.
* *
* @param env The environment to apply to each bound function * @param env The environment to apply to each bound function
* @param factory the Class to instantiate for each bound function * @param factory the Class to instantiate for each bound function
* @param names array of String names, one for each 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 }; return new LuaValue[] { v };
} }
@Override
public LuaValue call() { public LuaValue call() {
return argerror(1, "value expected"); return argerror(1, "value expected");
} }
@Override
public LuaValue call(LuaValue a) { public LuaValue call(LuaValue a) {
return call(); return call();
} }
@Override
public LuaValue call(LuaValue a, LuaValue b) { public LuaValue call(LuaValue a, LuaValue b) {
return call(a); return call(a);
} }
@Override
public LuaValue call(LuaValue a, LuaValue b, LuaValue c) { public LuaValue call(LuaValue a, LuaValue b, LuaValue c) {
return call(a, b); return call(a, b);
} }
@@ -240,6 +245,7 @@ abstract public class LibFunction extends LuaFunction {
return call(a, b, c); return call(a, b, c);
} }
@Override
public Varargs invoke(Varargs args) { public Varargs invoke(Varargs args) {
switch (args.narg()) { switch (args.narg()) {
case 0: case 0:

View File

@@ -10,7 +10,7 @@
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * 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 * 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.jse.JsePlatform#standardGlobals()} or
* {@link org.luaj.vm2.lib.jme.JmePlatform#standardGlobals()} * {@link org.luaj.vm2.lib.jme.JmePlatform#standardGlobals()}
* *
* <pre> * <pre>
* { * {
* &#64;code * &#64;code
@@ -62,14 +62,14 @@ import org.luaj.vm2.Varargs;
* System.out.println(globals.get("math").get("sqrt").call(LuaValue.valueOf(2))); * System.out.println(globals.get("math").get("sqrt").call(LuaValue.valueOf(2)));
* } * }
* </pre> * </pre>
* *
* When using {@link org.luaj.vm2.lib.jse.JsePlatform} as in this example, the * 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 * subclass {@link org.luaj.vm2.lib.jse.JseMathLib} will be included, which also
* includes this base functionality. * includes this base functionality.
* <p> * <p>
* To instantiate and use it directly, link it into your globals table via * To instantiate and use it directly, link it into your globals table via
* {@link LuaValue#load(LuaValue)} using code such as: * {@link LuaValue#load(LuaValue)} using code such as:
* *
* <pre> * <pre>
* { * {
* &#64;code * &#64;code
@@ -80,13 +80,13 @@ import org.luaj.vm2.Varargs;
* System.out.println(globals.get("math").get("sqrt").call(LuaValue.valueOf(2))); * System.out.println(globals.get("math").get("sqrt").call(LuaValue.valueOf(2)));
* } * }
* </pre> * </pre>
* *
* Doing so will ensure the library is properly initialized and loaded into the * Doing so will ensure the library is properly initialized and loaded into the
* globals table. * globals table.
* <p> * <p>
* This has been implemented to match as closely as possible the behavior in the * This has been implemented to match as closely as possible the behavior in the
* corresponding library in C. * corresponding library in C.
* *
* @see LibFunction * @see LibFunction
* @see org.luaj.vm2.lib.jse.JsePlatform * @see org.luaj.vm2.lib.jse.JsePlatform
* @see org.luaj.vm2.lib.jme.JmePlatform * @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 * containing the library functions, adding that table to the supplied
* environment, adding the table to package.loaded, and returning table as * environment, adding the table to package.loaded, and returning table as
* the return value. * the return value.
* *
* @param modname the module name supplied if this is loaded via 'require'. * @param modname the module name supplied if this is loaded via 'require'.
* @param env the environment to load into, typically a Globals * @param env the environment to load into, typically a Globals
* instance. * instance.
*/ */
@Override
public LuaValue call(LuaValue modname, LuaValue env) { public LuaValue call(LuaValue modname, LuaValue env) {
LuaTable math = new LuaTable(0, 30); LuaTable math = new LuaTable(0, 30);
math.set("abs", new abs()); math.set("abs", new abs());
@@ -152,6 +153,7 @@ public class MathLib extends TwoArgFunction {
} }
abstract protected static class UnaryOp extends OneArgFunction { abstract protected static class UnaryOp extends OneArgFunction {
@Override
public LuaValue call(LuaValue arg) { public LuaValue call(LuaValue arg) {
return valueOf(call(arg.checkdouble())); return valueOf(call(arg.checkdouble()));
} }
@@ -160,6 +162,7 @@ public class MathLib extends TwoArgFunction {
} }
abstract protected static class BinaryOp extends TwoArgFunction { abstract protected static class BinaryOp extends TwoArgFunction {
@Override
public LuaValue call(LuaValue x, LuaValue y) { public LuaValue call(LuaValue x, LuaValue y) {
return valueOf(call(x.checkdouble(), y.checkdouble())); return valueOf(call(x.checkdouble(), y.checkdouble()));
} }
@@ -168,38 +171,47 @@ public class MathLib extends TwoArgFunction {
} }
static final class abs extends UnaryOp { static final class abs extends UnaryOp {
@Override
protected double call(double d) { return Math.abs(d); } protected double call(double d) { return Math.abs(d); }
} }
static final class ceil extends UnaryOp { static final class ceil extends UnaryOp {
@Override
protected double call(double d) { return Math.ceil(d); } protected double call(double d) { return Math.ceil(d); }
} }
static final class cos extends UnaryOp { static final class cos extends UnaryOp {
@Override
protected double call(double d) { return Math.cos(d); } protected double call(double d) { return Math.cos(d); }
} }
static final class deg extends UnaryOp { static final class deg extends UnaryOp {
@Override
protected double call(double d) { return Math.toDegrees(d); } protected double call(double d) { return Math.toDegrees(d); }
} }
static final class floor extends UnaryOp { static final class floor extends UnaryOp {
@Override
protected double call(double d) { return Math.floor(d); } protected double call(double d) { return Math.floor(d); }
} }
static final class rad extends UnaryOp { static final class rad extends UnaryOp {
@Override
protected double call(double d) { return Math.toRadians(d); } protected double call(double d) { return Math.toRadians(d); }
} }
static final class sin extends UnaryOp { static final class sin extends UnaryOp {
@Override
protected double call(double d) { return Math.sin(d); } protected double call(double d) { return Math.sin(d); }
} }
static final class sqrt extends UnaryOp { static final class sqrt extends UnaryOp {
@Override
protected double call(double d) { return Math.sqrt(d); } protected double call(double d) { return Math.sqrt(d); }
} }
static final class tan extends UnaryOp { static final class tan extends UnaryOp {
@Override
protected double call(double d) { return Math.tan(d); } protected double call(double d) { return Math.tan(d); }
} }
@@ -210,12 +222,14 @@ public class MathLib extends TwoArgFunction {
this.mathlib = mathlib; this.mathlib = mathlib;
} }
@Override
protected double call(double d) { protected double call(double d) {
return mathlib.dpow_lib(Math.E, d); return mathlib.dpow_lib(Math.E, d);
} }
} }
static final class fmod extends TwoArgFunction { static final class fmod extends TwoArgFunction {
@Override
public LuaValue call(LuaValue xv, LuaValue yv) { public LuaValue call(LuaValue xv, LuaValue yv) {
if (xv.islong() && yv.islong()) { if (xv.islong() && yv.islong()) {
return valueOf(xv.tolong()%yv.tolong()); return valueOf(xv.tolong()%yv.tolong());
@@ -225,31 +239,35 @@ public class MathLib extends TwoArgFunction {
} }
static final class ldexp extends BinaryOp { static final class ldexp extends BinaryOp {
@Override
protected double call(double x, double y) { protected double call(double x, double y) {
// This is the behavior on os-x, windows differs in rounding behavior. // 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 { static final class pow extends BinaryOp {
@Override
protected double call(double x, double y) { protected double call(double x, double y) {
return MathLib.dpow_default(x, y); return MathLib.dpow_default(x, y);
} }
} }
static class frexp extends VarArgFunction { static class frexp extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) { public Varargs invoke(Varargs args) {
double x = args.checkdouble(1); double x = args.checkdouble(1);
if (x == 0) if (x == 0)
return varargsOf(ZERO, ZERO); return varargsOf(ZERO, ZERO);
long bits = Double.doubleToLongBits(x); long bits = Double.doubleToLongBits(x);
double m = ((bits & (~(-1L<<52)))+(1L<<52))*((bits >= 0)? (.5/(1L<<52)): (-.5/(1L<<52))); double m = ((bits & ~(-1L<<52))+(1L<<52))*(bits >= 0? .5/(1L<<52): -.5/(1L<<52));
double e = (((int) (bits>>52)) & 0x7ff)-1022; double e = ((int) (bits>>52) & 0x7ff)-1022;
return varargsOf(valueOf(m), valueOf(e)); return varargsOf(valueOf(m), valueOf(e));
} }
} }
static class max extends VarArgFunction { static class max extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) { public Varargs invoke(Varargs args) {
LuaValue m = args.checkvalue(1); LuaValue m = args.checkvalue(1);
for (int i = 2, n = args.narg(); i <= n; ++i) { for (int i = 2, n = args.narg(); i <= n; ++i) {
@@ -262,6 +280,7 @@ public class MathLib extends TwoArgFunction {
} }
static class min extends VarArgFunction { static class min extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) { public Varargs invoke(Varargs args) {
LuaValue m = args.checkvalue(1); LuaValue m = args.checkvalue(1);
for (int i = 2, n = args.narg(); i <= n; ++i) { for (int i = 2, n = args.narg(); i <= n; ++i) {
@@ -274,6 +293,7 @@ public class MathLib extends TwoArgFunction {
} }
static class modf extends VarArgFunction { static class modf extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) { public Varargs invoke(Varargs args) {
LuaValue n = args.arg1(); LuaValue n = args.arg1();
/* number is its own integer part, no fractional part */ /* number is its own integer part, no fractional part */
@@ -281,7 +301,7 @@ public class MathLib extends TwoArgFunction {
return varargsOf(n, valueOf(0.0)); return varargsOf(n, valueOf(0.0));
double x = n.checkdouble(); double x = n.checkdouble();
/* integer part (rounds toward zero) */ /* 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) */ /* fractional part (test needed for inf/-inf) */
double fracPart = x == intPart? 0.0: x-intPart; double fracPart = x == intPart? 0.0: x-intPart;
return varargsOf(valueOf(intPart), valueOf(fracPart)); return varargsOf(valueOf(intPart), valueOf(fracPart));
@@ -291,10 +311,12 @@ public class MathLib extends TwoArgFunction {
static class random extends LibFunction { static class random extends LibFunction {
Random random = new Random(); Random random = new Random();
@Override
public LuaValue call() { public LuaValue call() {
return valueOf(random.nextDouble()); return valueOf(random.nextDouble());
} }
@Override
public LuaValue call(LuaValue a) { public LuaValue call(LuaValue a) {
int m = a.checkint(); int m = a.checkint();
if (m < 1) if (m < 1)
@@ -302,6 +324,7 @@ public class MathLib extends TwoArgFunction {
return valueOf(1+random.nextInt(m)); return valueOf(1+random.nextInt(m));
} }
@Override
public LuaValue call(LuaValue a, LuaValue b) { public LuaValue call(LuaValue a, LuaValue b) {
int m = a.checkint(); int m = a.checkint();
int n = b.checkint(); int n = b.checkint();
@@ -319,6 +342,7 @@ public class MathLib extends TwoArgFunction {
this.random = random; this.random = random;
} }
@Override
public LuaValue call(LuaValue arg) { public LuaValue call(LuaValue arg) {
long seed = arg.checklong(); long seed = arg.checklong();
random.random = new Random(seed); random.random = new Random(seed);

View File

@@ -10,7 +10,7 @@
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -40,7 +40,7 @@ import org.luaj.vm2.Varargs;
* <p> * <p>
* See {@link LibFunction} for more information on implementation libraries and * See {@link LibFunction} for more information on implementation libraries and
* library functions. * library functions.
* *
* @see #call(LuaValue) * @see #call(LuaValue)
* @see LibFunction * @see LibFunction
* @see ZeroArgFunction * @see ZeroArgFunction
@@ -50,24 +50,29 @@ import org.luaj.vm2.Varargs;
*/ */
abstract public class OneArgFunction extends LibFunction { abstract public class OneArgFunction extends LibFunction {
@Override
abstract public LuaValue call(LuaValue arg); abstract public LuaValue call(LuaValue arg);
/** Default constructor */ /** Default constructor */
public OneArgFunction() { public OneArgFunction() {
} }
@Override
public final LuaValue call() { public final LuaValue call() {
return call(NIL); return call(NIL);
} }
@Override
public final LuaValue call(LuaValue arg1, LuaValue arg2) { public final LuaValue call(LuaValue arg1, LuaValue arg2) {
return call(arg1); return call(arg1);
} }
@Override
public LuaValue call(LuaValue arg1, LuaValue arg2, LuaValue arg3) { public LuaValue call(LuaValue arg1, LuaValue arg2, LuaValue arg3) {
return call(arg1); return call(arg1);
} }
@Override
public Varargs invoke(Varargs varargs) { public Varargs invoke(Varargs varargs) {
return call(varargs.arg1()); return call(varargs.arg1());
} }

View File

@@ -10,7 +10,7 @@
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * 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 * 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.jse.JsePlatform#standardGlobals()} or
* {@link org.luaj.vm2.lib.jme.JmePlatform#standardGlobals()} * {@link org.luaj.vm2.lib.jme.JmePlatform#standardGlobals()}
* *
* <pre> * <pre>
* { * {
* &#64;code * &#64;code
@@ -65,14 +65,14 @@ import org.luaj.vm2.Varargs;
* System.out.println(globals.get("os").get("time").call()); * System.out.println(globals.get("os").get("time").call());
* } * }
* </pre> * </pre>
* *
* In this example the platform-specific {@link org.luaj.vm2.lib.jse.JseOsLib} * 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 * library will be loaded, which will include the base functionality provided by
* this class. * this class.
* <p> * <p>
* To instantiate and use it directly, link it into your globals table via * To instantiate and use it directly, link it into your globals table via
* {@link LuaValue#load(LuaValue)} using code such as: * {@link LuaValue#load(LuaValue)} using code such as:
* *
* <pre> * <pre>
* { * {
* &#64;code * &#64;code
@@ -84,7 +84,7 @@ import org.luaj.vm2.Varargs;
* } * }
* </pre> * </pre>
* <p> * <p>
* *
* @see LibFunction * @see LibFunction
* @see org.luaj.vm2.lib.jse.JseOsLib * @see org.luaj.vm2.lib.jse.JseOsLib
* @see org.luaj.vm2.lib.jse.JsePlatform * @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 * containing the library functions, adding that table to the supplied
* environment, adding the table to package.loaded, and returning table as * environment, adding the table to package.loaded, and returning table as
* the return value. * the return value.
* *
* @param modname the module name supplied if this is loaded via 'require'. * @param modname the module name supplied if this is loaded via 'require'.
* @param env the environment to load into, typically a Globals * @param env the environment to load into, typically a Globals
* instance. * instance.
*/ */
@Override
public LuaValue call(LuaValue modname, LuaValue env) { public LuaValue call(LuaValue modname, LuaValue env) {
globals = env.checkglobals(); globals = env.checkglobals();
LuaTable os = new LuaTable(); LuaTable os = new LuaTable();
@@ -149,6 +150,7 @@ public class OsLib extends TwoArgFunction {
this.name = name; this.name = name;
} }
@Override
public Varargs invoke(Varargs args) { public Varargs invoke(Varargs args) {
try { try {
switch (opcode) { 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, * Returns the number of seconds from time t1 to time t2. In POSIX, Windows,
* and some other systems, this value is exactly t2-t1. * and some other systems, this value is exactly t2-t1.
* *
* @param t2 * @param t2
* @param t1 * @param t1
* @return diffeence in time values, in seconds * @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 * 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 * the os.time function for a description of this value). Otherwise, date
* formats the current time. * formats the current time.
* *
* Date returns the date as a string, formatted according to the same rules * Date returns the date as a string, formatted according to the same rules
* as ANSII strftime, but without support for %g, %G, or %V. * as ANSII strftime, but without support for %g, %G, or %V.
* *
* When called without arguments, date returns a reasonable date and time * When called without arguments, date returns a reasonable date and time
* representation that depends on the host system and on the current locale * representation that depends on the host system and on the current locale
* (that is, os.date() is equivalent to os.date("%c")). * (that is, os.date() is equivalent to os.date("%c")).
* *
* @param format * @param format
* @param time time since epoch, or -1 if not supplied * @param time time since epoch, or -1 if not supplied
* @return a LString or a LTable containing date and time, formatted * @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)); result.append(String.valueOf(100+d.get(Calendar.HOUR_OF_DAY)).substring(1));
break; break;
case 'I': 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; break;
case 'j': { // day of year. case 'j': { // day of year.
Calendar y0 = beginningOfYear(d); 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, * 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 * which is system-dependent. If command is absent, then it returns nonzero
* if a shell is available and zero otherwise. * if a shell is available and zero otherwise.
* *
* @param command command to pass to the system * @param command command to pass to the system
*/ */
protected Varargs execute(String command) { 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 * Calls the C function exit, with an optional code, to terminate the host
* program. * program.
* *
* @param code * @param code
*/ */
protected void exit(int 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 * Returns the value of the process environment variable varname, or the
* System property value for varname, or null if the variable is not defined * System property value for varname, or null if the variable is not defined
* in either environment. * in either environment.
* *
* The default implementation, which is used by the JmePlatform, only * The default implementation, which is used by the JmePlatform, only
* queryies System.getProperty(). * queryies System.getProperty().
* *
* The JsePlatform overrides this behavior and returns the environment * The JsePlatform overrides this behavior and returns the environment
* variable value using System.getenv() if it exists, or the System property * variable value using System.getenv() if it exists, or the System property
* value if it does not. * value if it does not.
* *
* A SecurityException may be thrown if access is not allowed for 'varname'. * A SecurityException may be thrown if access is not allowed for 'varname'.
* *
* @param varname * @param varname
* @return String value, or null if not defined * @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 * Deletes the file or directory with the given name. Directories must be
* empty to be removed. If this function fails, it throws and IOException * empty to be removed. If this function fails, it throws and IOException
* *
* @param filename * @param filename
* @throws IOException if it fails * @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 * Renames file or directory named oldname to newname. If this function
* fails,it throws and IOException * fails,it throws and IOException
* *
* @param oldname old file name * @param oldname old file name
* @param newname new file name * @param newname new file name
* @throws IOException if it fails * @throws IOException if it fails
@@ -465,14 +467,14 @@ public class OsLib extends TwoArgFunction {
* locale; category is an optional string describing which category to * locale; category is an optional string describing which category to
* change: "all", "collate", "ctype", "monetary", "numeric", or "time"; the * change: "all", "collate", "ctype", "monetary", "numeric", or "time"; the
* default category is "all". * default category is "all".
* *
* If locale is the empty string, the current locale is set to an * If locale is the empty string, the current locale is set to an
* implementation- defined native locale. If locale is the string "C", the * implementation- defined native locale. If locale is the string "C", the
* current locale is set to the standard C locale. * current locale is set to the standard C locale.
* *
* When called with null as the first argument, this function only returns * When called with null as the first argument, this function only returns
* the name of the current locale for the given category. * the name of the current locale for the given category.
* *
* @param locale * @param locale
* @param category * @param category
* @return the name of the new locale, or null if the request cannot be * @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, * 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 * sec, and isdst (for a description of these fields, see the os.date
* function). * function).
* *
* @param table * @param table
* @return long value for the time * @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. * 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 * The file must be explicitly opened before its use and explicitly removed
* when no longer needed. * when no longer needed.
* *
* On some systems (POSIX), this function also creates a file with that * On some systems (POSIX), this function also creates a file with that
* name, to avoid security risks. (Someone else might create the file with * name, to avoid security risks. (Someone else might create the file with
* wrong permissions in the time between getting the name and creating the * 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 * file.) You still have to open the file to use it and to remove it (even
* if you do not use it). * if you do not use it).
* *
* @return String filename to use * @return String filename to use
*/ */
protected String tmpname() { protected String tmpname() {
synchronized (OsLib.class) { 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 * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -22,6 +22,7 @@
package org.luaj.vm2.lib; package org.luaj.vm2.lib;
import java.io.InputStream; import java.io.InputStream;
import java.nio.file.FileSystems;
import org.luaj.vm2.Globals; import org.luaj.vm2.Globals;
import org.luaj.vm2.LuaFunction; 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 * Subclass of {@link LibFunction} which implements the lua standard package and
* module library functions. * module library functions.
* *
* <h3>Lua Environment Variables</h3> The following variables are available to * <h3>Lua Environment Variables</h3> The following variables are available to
* lua scrips when this library has been loaded: * lua scrips when this library has been loaded:
* <ul> * <ul>
@@ -44,18 +45,18 @@ import org.luaj.vm2.Varargs;
* <li><code>"package.searchers"</code> Lua table of functions that search for * <li><code>"package.searchers"</code> Lua table of functions that search for
* object to load. * object to load.
* </ul> * </ul>
* *
* <h3>Java Environment Variables</h3> These Java environment variables affect * <h3>Java Environment Variables</h3> These Java environment variables affect
* the library behavior: * the library behavior:
* <ul> * <ul>
* <li><code>"luaj.package.path"</code> Initial value for * <li><code>"luaj.package.path"</code> Initial value for
* <code>"package.path"</code>. Default value is <code>"?.lua"</code> * <code>"package.path"</code>. Default value is <code>"?.lua"</code>
* </ul> * </ul>
* *
* <h3>Loading</h3> Typically, this library is included as part of a call to * <h3>Loading</h3> Typically, this library is included as part of a call to
* either {@link org.luaj.vm2.lib.jse.JsePlatform#standardGlobals()} or * either {@link org.luaj.vm2.lib.jse.JsePlatform#standardGlobals()} or
* {@link org.luaj.vm2.lib.jme.JmePlatform#standardGlobals()} * {@link org.luaj.vm2.lib.jme.JmePlatform#standardGlobals()}
* *
* <pre> * <pre>
* {@code * {@code
* Globals globals = JsePlatform.standardGlobals(); * Globals globals = JsePlatform.standardGlobals();
@@ -65,7 +66,7 @@ import org.luaj.vm2.Varargs;
* <p> * <p>
* To instantiate and use it directly, link it into your globals table via * To instantiate and use it directly, link it into your globals table via
* {@link LuaValue#load(LuaValue)} using code such as: * {@link LuaValue#load(LuaValue)} using code such as:
* *
* <pre> * <pre>
* { * {
* &#64;code * &#64;code
@@ -75,14 +76,14 @@ import org.luaj.vm2.Varargs;
* System.out.println(globals.get("require").call("foo")); * System.out.println(globals.get("require").call("foo"));
* } * }
* </pre> * </pre>
* *
* <h3>Limitations</h3> This library has been implemented to match as closely as * <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 * possible the behavior in the corresponding library in C. However, the default
* filesystem search semantics are different and delegated to the bas library as * 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} * outlined in the {@link BaseLib} and {@link org.luaj.vm2.lib.jse.JseBaseLib}
* documentation. * documentation.
* <p> * <p>
* *
* @see LibFunction * @see LibFunction
* @see BaseLib * @see BaseLib
* @see org.luaj.vm2.lib.jse.JseBaseLib * @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 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() {} public PackageLib() {}
@@ -151,11 +152,12 @@ public class PackageLib extends TwoArgFunction {
* functions to the supplied environment, and returning it as the return * functions to the supplied environment, and returning it as the return
* value. It also creates the package.preload and package.loaded tables for * value. It also creates the package.preload and package.loaded tables for
* use by other libraries. * use by other libraries.
* *
* @param modname the module name supplied if this is loaded via 'require'. * @param modname the module name supplied if this is loaded via 'require'.
* @param env the environment to load into, typically a Globals * @param env the environment to load into, typically a Globals
* instance. * instance.
*/ */
@Override
public LuaValue call(LuaValue modname, LuaValue env) { public LuaValue call(LuaValue modname, LuaValue env) {
globals = env.checkglobals(); globals = env.checkglobals();
globals.set("require", new require()); globals.set("require", new require());
@@ -190,6 +192,7 @@ public class PackageLib extends TwoArgFunction {
package_.set(_PATH, LuaValue.valueOf(newLuaPath)); package_.set(_PATH, LuaValue.valueOf(newLuaPath));
} }
@Override
public String tojstring() { public String tojstring() {
return "package"; return "package";
} }
@@ -198,23 +201,23 @@ public class PackageLib extends TwoArgFunction {
/** /**
* require (modname) * require (modname)
* *
* Loads the given module. The function starts by looking into the * Loads the given module. The function starts by looking into the
* package.loaded table to determine whether modname is already loaded. If * package.loaded table to determine whether modname is already loaded. If
* it is, then require returns the value stored at package.loaded[modname]. * it is, then require returns the value stored at package.loaded[modname].
* Otherwise, it tries to find a loader for the module. * Otherwise, it tries to find a loader for the module.
* *
* To find a loader, require is guided by the package.searchers sequence. By * 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 * changing this sequence, we can change how require looks for a module. The
* following explanation is based on the default configuration for * following explanation is based on the default configuration for
* package.searchers. * package.searchers.
* *
* First require queries package.preload[modname]. If it has a value, this * First require queries package.preload[modname]. If it has a value, this
* value (which should be a function) is the loader. Otherwise require * 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 * 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 * also fails, it searches for a Java loader using the classpath, using the
* public default constructor, and casting the instance to LuaFunction. * public default constructor, and casting the instance to LuaFunction.
* *
* Once a loader is found, require calls the loader with two arguments: * 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 * 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 * 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 * value and has not assigned any value to package.loaded[modname], then
* require assigns true to this entry. In any case, require returns the * require assigns true to this entry. In any case, require returns the
* final value of package.loaded[modname]. * final value of package.loaded[modname].
* *
* If there is any error loading or running the module, or if it cannot find * 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. * any loader for the module, then require raises an error.
*/ */
public class require extends OneArgFunction { public class require extends OneArgFunction {
@Override
public LuaValue call(LuaValue arg) { public LuaValue call(LuaValue arg) {
LuaString name = arg.checkstring(); LuaString name = arg.checkstring();
LuaValue loaded = package_.get(_LOADED); LuaValue loaded = package_.get(_LOADED);
@@ -269,6 +273,7 @@ public class PackageLib extends TwoArgFunction {
} }
public static class loadlib extends VarArgFunction { public static class loadlib extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) { public Varargs invoke(Varargs args) {
args.checkstring(1); args.checkstring(1);
return varargsOf(NIL, valueOf("dynamic libraries not enabled"), valueOf("absent")); 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 { public class preload_searcher extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) { public Varargs invoke(Varargs args) {
LuaString name = args.checkstring(1); LuaString name = args.checkstring(1);
LuaValue val = package_.get(_PRELOAD).get(name); LuaValue val = package_.get(_PRELOAD).get(name);
@@ -284,6 +290,7 @@ public class PackageLib extends TwoArgFunction {
} }
public class lua_searcher extends VarArgFunction { public class lua_searcher extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) { public Varargs invoke(Varargs args) {
LuaString name = args.checkstring(1); LuaString name = args.checkstring(1);
@@ -311,6 +318,7 @@ public class PackageLib extends TwoArgFunction {
} }
public class searchpath extends VarArgFunction { public class searchpath extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) { public Varargs invoke(Varargs args) {
String name = args.checkjstring(1); String name = args.checkjstring(1);
String path = args.checkjstring(2); String path = args.checkjstring(2);
@@ -358,6 +366,7 @@ public class PackageLib extends TwoArgFunction {
} }
public class java_searcher extends VarArgFunction { public class java_searcher extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) { public Varargs invoke(Varargs args) {
String name = args.checkjstring(1); String name = args.checkjstring(1);
String classname = toClassname(name); String classname = toClassname(name);
@@ -385,11 +394,11 @@ public class PackageLib extends TwoArgFunction {
j -= 4; j -= 4;
for (int k = 0; k < j; k++) { for (int k = 0; k < j; k++) {
char c = filename.charAt(k); char c = filename.charAt(k);
if ((!isClassnamePart(c)) || (c == '/') || (c == '\\')) { if (!isClassnamePart(c) || c == '/' || c == '\\') {
StringBuffer sb = new StringBuffer(j); StringBuffer sb = new StringBuffer(j);
for (int i = 0; i < j; i++) { for (int i = 0; i < j; i++) {
c = filename.charAt(i); c = filename.charAt(i);
sb.append((isClassnamePart(c))? c: ((c == '/') || (c == '\\'))? '.': '_'); sb.append(isClassnamePart(c)? c: c == '/' || c == '\\'? '.': '_');
} }
return sb.toString(); return sb.toString();
} }
@@ -398,7 +407,7 @@ public class PackageLib extends TwoArgFunction {
} }
private static final boolean isClassnamePart(char c) { 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; return true;
switch (c) { switch (c) {
case '.': case '.':

View File

@@ -10,7 +10,7 @@
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -38,7 +38,7 @@ import org.luaj.vm2.Globals;
* <p> * <p>
* The io library does not use this API for file manipulation. * The io library does not use this API for file manipulation.
* <p> * <p>
* *
* @see BaseLib * @see BaseLib
* @see Globals#finder * @see Globals#finder
* @see org.luaj.vm2.lib.jse.JseBaseLib * @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. * Try to open a file, or return null if not found.
* *
* @see org.luaj.vm2.lib.BaseLib * @see org.luaj.vm2.lib.BaseLib
* @see org.luaj.vm2.lib.jse.JseBaseLib * @see org.luaj.vm2.lib.jse.JseBaseLib
* *
* @param filename * @param filename
* @return InputStream, or null if not found. * @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 * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * 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 * 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.jse.JsePlatform#standardGlobals()} or
* {@link org.luaj.vm2.lib.jme.JmePlatform#standardGlobals()} * {@link org.luaj.vm2.lib.jme.JmePlatform#standardGlobals()}
* *
* <pre> * <pre>
* { * {
* &#64;code * &#64;code
@@ -50,7 +50,7 @@ import org.luaj.vm2.compiler.DumpState;
* <p> * <p>
* To instantiate and use it directly, link it into your globals table via * To instantiate and use it directly, link it into your globals table via
* {@link LuaValue#load(LuaValue)} using code such as: * {@link LuaValue#load(LuaValue)} using code such as:
* *
* <pre> * <pre>
* { * {
* &#64;code * &#64;code
@@ -63,7 +63,7 @@ import org.luaj.vm2.compiler.DumpState;
* </pre> * </pre>
* <p> * <p>
* This is a direct port of the corresponding library in C. * This is a direct port of the corresponding library in C.
* *
* @see LibFunction * @see LibFunction
* @see org.luaj.vm2.lib.jse.JsePlatform * @see org.luaj.vm2.lib.jse.JsePlatform
* @see org.luaj.vm2.lib.jme.JmePlatform * @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, * used in a server environment, sandboxing should be used. In particular,
* the {@link LuaString#s_metatable} table should probably be made * the {@link LuaString#s_metatable} table should probably be made
* read-only. * read-only.
* *
* @param modname the module name supplied if this is loaded via 'require'. * @param modname the module name supplied if this is loaded via 'require'.
* @param env the environment to load into, typically a Globals * @param env the environment to load into, typically a Globals
* instance. * instance.
*/ */
@Override
public LuaValue call(LuaValue modname, LuaValue env) { public LuaValue call(LuaValue modname, LuaValue env) {
LuaTable string = new LuaTable(); LuaTable string = new LuaTable();
string.set("byte", new _byte()); string.set("byte", new _byte());
@@ -126,15 +127,16 @@ public class StringLib extends TwoArgFunction {
/** /**
* string.byte (s [, i [, j]]) * string.byte (s [, i [, j]])
* *
* Returns the internal numerical codes of the characters s[i], s[i+1], ..., * 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. * 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. * Note that numerical codes are not necessarily portable across platforms.
* *
* @param args the calling args * @param args the calling args
*/ */
static final class _byte extends VarArgFunction { static final class _byte extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) { public Varargs invoke(Varargs args) {
LuaString s = args.checkstring(1); LuaString s = args.checkstring(1);
int l = s.m_length; int l = s.m_length;
@@ -147,7 +149,7 @@ public class StringLib extends TwoArgFunction {
pose = l; pose = l;
if (posi > pose) if (posi > pose)
return NONE; /* empty interval; return no values */ return NONE; /* empty interval; return no values */
n = (int) (pose-posi+1); n = pose-posi+1;
if (posi+n <= pose) /* overflow? */ if (posi+n <= pose) /* overflow? */
error("string slice too long"); error("string slice too long");
LuaValue[] v = new LuaValue[n]; LuaValue[] v = new LuaValue[n];
@@ -159,16 +161,17 @@ public class StringLib extends TwoArgFunction {
/** /**
* string.char (...) * string.char (...)
* *
* Receives zero or more integers. Returns a string with length equal to the * Receives zero or more integers. Returns a string with length equal to the
* number of arguments, in which each character has the internal numerical * number of arguments, in which each character has the internal numerical
* code equal to its corresponding argument. * code equal to its corresponding argument.
* *
* Note that numerical codes are not necessarily portable across platforms. * Note that numerical codes are not necessarily portable across platforms.
* *
* @param args the calling VM * @param args the calling VM
*/ */
static final class _char extends VarArgFunction { static final class _char extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) { public Varargs invoke(Varargs args) {
int n = args.narg(); int n = args.narg();
byte[] bytes = new byte[n]; byte[] bytes = new byte[n];
@@ -184,16 +187,17 @@ public class StringLib extends TwoArgFunction {
/** /**
* string.dump (function[, stripDebug]) * string.dump (function[, stripDebug])
* *
* Returns a string containing a binary representation of the given * 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, so that a later loadstring on this string returns a copy of the
* function. function must be a Lua function without upvalues. Boolean param * function. function must be a Lua function without upvalues. Boolean param
* stripDebug - true to strip debugging info, false otherwise. The default * stripDebug - true to strip debugging info, false otherwise. The default
* value for stripDebug is true. * value for stripDebug is true.
* *
* TODO: port dumping code as optional add-on * TODO: port dumping code as optional add-on
*/ */
static final class dump extends VarArgFunction { static final class dump extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) { public Varargs invoke(Varargs args) {
LuaValue f = args.checkfunction(1); LuaValue f = args.checkfunction(1);
ByteArrayOutputStream baos = new ByteArrayOutputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream();
@@ -208,7 +212,7 @@ public class StringLib extends TwoArgFunction {
/** /**
* string.find (s, pattern [, init [, plain]]) * string.find (s, pattern [, init [, plain]])
* *
* Looks for the first match of pattern in the string s. If it finds a * 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 * match, then find returns the indices of s where this occurrence starts
* and ends; otherwise, it returns nil. A third, optional numerical argument * 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 * off the pattern matching facilities, so the function does a plain "find
* substring" operation, with no characters in pattern being considered * substring" operation, with no characters in pattern being considered
* "magic". Note that if plain is given, then init must be given as well. * "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 * If the pattern has captures, then in a successful match the captured
* values are also returned, after the two indices. * values are also returned, after the two indices.
*/ */
static final class find extends VarArgFunction { static final class find extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) { public Varargs invoke(Varargs args) {
return str_find_aux(args, true); return str_find_aux(args, true);
} }
@@ -229,7 +234,7 @@ public class StringLib extends TwoArgFunction {
/** /**
* string.format (formatstring, ...) * string.format (formatstring, ...)
* *
* Returns a formatted version of its variable number of arguments following * Returns a formatted version of its variable number of arguments following
* the description given in its first argument (which must be a string). The * 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 * 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') * string.format('%q', 'a string with "quotes" and \n new line')
* *
* will produce the string: "a string with \"quotes\" and \ 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 * 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. * argument, whereas q and s expect a string.
* *
* This function does not accept string values containing embedded zeros, * This function does not accept string values containing embedded zeros,
* except as arguments to the q option. * except as arguments to the q option.
*/ */
final class format extends VarArgFunction { final class format extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) { public Varargs invoke(Varargs args) {
LuaString fmt = args.checkstring(1); LuaString fmt = args.checkstring(1);
final int n = fmt.length(); final int n = fmt.length();
@@ -375,7 +381,7 @@ public class StringLib extends TwoArgFunction {
boolean moreFlags = true; boolean moreFlags = true;
while ( moreFlags ) { while ( moreFlags ) {
switch (c = ((p < n)? strfrmt.luaByte(p++): 0)) { switch (c = p < n? strfrmt.luaByte(p++): 0) {
case '-': case '-':
leftAdjust = true; leftAdjust = true;
break; break;
@@ -402,22 +408,22 @@ public class StringLib extends TwoArgFunction {
width = -1; width = -1;
if (Character.isDigit((char) c)) { if (Character.isDigit((char) c)) {
width = c-'0'; width = c-'0';
c = ((p < n)? strfrmt.luaByte(p++): 0); c = p < n? strfrmt.luaByte(p++): 0;
if (Character.isDigit((char) c)) { if (Character.isDigit((char) c)) {
width = width*10+(c-'0'); width = width*10+c-'0';
c = ((p < n)? strfrmt.luaByte(p++): 0); c = p < n? strfrmt.luaByte(p++): 0;
} }
} }
precision = -1; precision = -1;
if (c == '.') { if (c == '.') {
c = ((p < n)? strfrmt.luaByte(p++): 0); c = p < n? strfrmt.luaByte(p++): 0;
if (Character.isDigit((char) c)) { if (Character.isDigit((char) c)) {
precision = c-'0'; precision = c-'0';
c = ((p < n)? strfrmt.luaByte(p++): 0); c = p < n? strfrmt.luaByte(p++): 0;
if (Character.isDigit((char) c)) { if (Character.isDigit((char) c)) {
precision = precision*10+(c-'0'); precision = precision*10+c-'0';
c = ((p < n)? strfrmt.luaByte(p++): 0); c = p < n? strfrmt.luaByte(p++): 0;
} }
} }
} }
@@ -527,14 +533,14 @@ public class StringLib extends TwoArgFunction {
/** /**
* string.gmatch (s, pattern) * string.gmatch (s, pattern)
* *
* Returns an iterator function that, each time it is called, returns the * Returns an iterator function that, each time it is called, returns the
* next captures from pattern over string s. If pattern specifies no * next captures from pattern over string s. If pattern specifies no
* captures, then the whole match is produced in each call. * captures, then the whole match is produced in each call.
* *
* As an example, the following loop s = "hello world from Lua" for w in * As an example, the following loop s = "hello world from Lua" for w in
* string.gmatch(s, "%a+") do print(w) end * string.gmatch(s, "%a+") do print(w) end
* *
* will iterate over all the words from string s, printing one per line. The * 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 * 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, * 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. * anchor, as this would prevent the iteration.
*/ */
static final class gmatch extends VarArgFunction { static final class gmatch extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) { public Varargs invoke(Varargs args) {
LuaString src = args.checkstring(1); LuaString src = args.checkstring(1);
LuaString pat = args.checkstring(2); LuaString pat = args.checkstring(2);
@@ -564,6 +571,7 @@ public class StringLib extends TwoArgFunction {
this.lastmatch = -1; this.lastmatch = -1;
} }
@Override
public Varargs invoke(Varargs args) { public Varargs invoke(Varargs args) {
for (; soffset <= srclen; soffset++) { for (; soffset <= srclen; soffset++) {
ms.reset(); ms.reset();
@@ -584,30 +592,30 @@ public class StringLib extends TwoArgFunction {
* replacement string specified by repl, which may be a string, a table, or * 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 * a function. gsub also returns, as its second value, the total number of
* matches that occurred. * matches that occurred.
* *
* If repl is a string, then its value is used for replacement. The * 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 * 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 * 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 * captured substring (see below). The sequence %0 stands for the whole
* match. The sequence %% stands for a single %. * match. The sequence %% stands for a single %.
* *
* If repl is a table, then the table is queried for every match, using the * 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 * first capture as the key; if the pattern specifies no captures, then the
* whole match is used as the key. * whole match is used as the key.
* *
* If repl is a function, then this function is called every time a match * 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 * occurs, with all captured substrings passed as arguments, in order; if
* the pattern specifies no captures, then the whole match is passed as a * the pattern specifies no captures, then the whole match is passed as a
* sole argument. * sole argument.
* *
* If the value returned by the table query or by the function call is a * 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, * 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 * if it is false or nil, then there is no replacement (that is, the
* original match is kept in the string). * original match is kept in the string).
* *
* Here are some examples: x = string.gsub("hello world", "(%w+)", "%1 %1") * Here are some examples: x = string.gsub("hello world", "(%w+)", "%1 %1")
* --> x="hello hello world world" * --> x="hello hello world world"
* *
* x = string.gsub("hello world", "%w+", "%0 %0", 1) --> x="hello hello * x = string.gsub("hello world", "%w+", "%0 %0", 1) --> x="hello hello
* world" * world"
* *
@@ -624,6 +632,7 @@ public class StringLib extends TwoArgFunction {
* string.gsub("$name-$version.tar.gz", "%$(%w+)", t) --> x="lua-5.1.tar.gz" * string.gsub("$name-$version.tar.gz", "%$(%w+)", t) --> x="lua-5.1.tar.gz"
*/ */
static final class gsub extends VarArgFunction { static final class gsub extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) { public Varargs invoke(Varargs args) {
LuaString src = args.checkstring(1); LuaString src = args.checkstring(1);
final int srclen = src.length(); final int srclen = src.length();
@@ -659,11 +668,12 @@ public class StringLib extends TwoArgFunction {
/** /**
* string.len (s) * string.len (s)
* *
* Receives a string and returns its length. The empty string "" has length * Receives a string and returns its length. The empty string "" has length
* 0. Embedded zeros are counted, so "a\000bc\000" has length 5. * 0. Embedded zeros are counted, so "a\000bc\000" has length 5.
*/ */
static final class len extends OneArgFunction { static final class len extends OneArgFunction {
@Override
public LuaValue call(LuaValue arg) { public LuaValue call(LuaValue arg) {
return arg.checkstring().len(); return arg.checkstring().len();
} }
@@ -671,13 +681,14 @@ public class StringLib extends TwoArgFunction {
/** /**
* string.lower (s) * string.lower (s)
* *
* Receives a string and returns a copy of this string with all uppercase * Receives a string and returns a copy of this string with all uppercase
* letters changed to lowercase. All other characters are left unchanged. * letters changed to lowercase. All other characters are left unchanged.
* The definition of what an uppercase letter is depends on the current * The definition of what an uppercase letter is depends on the current
* locale. * locale.
*/ */
static final class lower extends OneArgFunction { static final class lower extends OneArgFunction {
@Override
public LuaValue call(LuaValue arg) { public LuaValue call(LuaValue arg) {
return valueOf(arg.checkjstring().toLowerCase()); return valueOf(arg.checkjstring().toLowerCase());
} }
@@ -685,7 +696,7 @@ public class StringLib extends TwoArgFunction {
/** /**
* string.match (s, pattern [, init]) * string.match (s, pattern [, init])
* *
* Looks for the first match of pattern in the string s. If it finds one, * 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 * then match returns the captures from the pattern; otherwise it returns
* nil. If pattern specifies no captures, then the whole match is returned. * 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. * search; its default value is 1 and may be negative.
*/ */
static final class match extends VarArgFunction { static final class match extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) { public Varargs invoke(Varargs args) {
return str_find_aux(args, false); return str_find_aux(args, false);
} }
@@ -700,10 +712,11 @@ public class StringLib extends TwoArgFunction {
/** /**
* string.rep (s, n) * string.rep (s, n)
* *
* Returns a string that is the concatenation of n copies of the string s. * Returns a string that is the concatenation of n copies of the string s.
*/ */
static final class rep extends VarArgFunction { static final class rep extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) { public Varargs invoke(Varargs args) {
LuaString s = args.checkstring(1); LuaString s = args.checkstring(1);
int n = args.checkint(2); int n = args.checkint(2);
@@ -718,10 +731,11 @@ public class StringLib extends TwoArgFunction {
/** /**
* string.reverse (s) * string.reverse (s)
* *
* Returns a string that is the string s reversed. * Returns a string that is the string s reversed.
*/ */
static final class reverse extends OneArgFunction { static final class reverse extends OneArgFunction {
@Override
public LuaValue call(LuaValue arg) { public LuaValue call(LuaValue arg) {
LuaString s = arg.checkstring(); LuaString s = arg.checkstring();
int n = s.length(); int n = s.length();
@@ -734,7 +748,7 @@ public class StringLib extends TwoArgFunction {
/** /**
* string.sub (s, i [, j]) * string.sub (s, i [, j])
* *
* Returns the substring of s that starts at i and continues until j; i and * 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 * 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 * (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. * -i) returns a suffix of s with length i.
*/ */
static final class sub extends VarArgFunction { static final class sub extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) { public Varargs invoke(Varargs args) {
final LuaString s = args.checkstring(1); final LuaString s = args.checkstring(1);
final int l = s.length(); final int l = s.length();
@@ -764,13 +779,14 @@ public class StringLib extends TwoArgFunction {
/** /**
* string.upper (s) * string.upper (s)
* *
* Receives a string and returns a copy of this string with all lowercase * Receives a string and returns a copy of this string with all lowercase
* letters changed to uppercase. All other characters are left unchanged. * letters changed to uppercase. All other characters are left unchanged.
* The definition of what a lowercase letter is depends on the current * The definition of what a lowercase letter is depends on the current
* locale. * locale.
*/ */
static final class upper extends OneArgFunction { static final class upper extends OneArgFunction {
@Override
public LuaValue call(LuaValue arg) { public LuaValue call(LuaValue arg) {
return valueOf(arg.checkjstring().toUpperCase()); return valueOf(arg.checkjstring().toUpperCase());
} }
@@ -824,7 +840,7 @@ public class StringLib extends TwoArgFunction {
} }
static int posrelat(int pos, int len) { static int posrelat(int pos, int len) {
return (pos >= 0)? pos: len+pos+1; return pos >= 0? pos: len+pos+1;
} }
// Pattern matching implementation // Pattern matching implementation
@@ -856,11 +872,11 @@ public class StringLib extends TwoArgFunction {
final char c = (char) i; final char c = (char) i;
CHAR_TABLE[i] = (byte) ((Character.isDigit(c)? MASK_DIGIT: 0) CHAR_TABLE[i] = (byte) ((Character.isDigit(c)? MASK_DIGIT: 0)
| (Character.isLowerCase(c)? MASK_LOWERCASE: 0) | (Character.isUpperCase(c)? MASK_UPPERCASE: 0) | (Character.isLowerCase(c)? MASK_LOWERCASE: 0) | (Character.isUpperCase(c)? MASK_UPPERCASE: 0)
| ((c < ' ' || c == 0x7F)? MASK_CONTROL: 0)); | (c < ' ' || c == 0x7F? MASK_CONTROL: 0));
if ((c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F') || (c >= '0' && c <= '9')) { if (c >= 'a' && c <= 'f' || c >= 'A' && c <= 'F' || c >= '0' && c <= '9') {
CHAR_TABLE[i] |= MASK_HEXDIGIT; 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; CHAR_TABLE[i] |= MASK_PUNCT;
} }
if ((CHAR_TABLE[i] & (MASK_LOWERCASE | MASK_UPPERCASE)) != 0) { 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['\t'] |= MASK_SPACE;
CHAR_TABLE[0x0B /* '\v' */ ] |= MASK_SPACE; CHAR_TABLE[0x0B /* '\v' */ ] |= MASK_SPACE;
CHAR_TABLE['\f'] |= MASK_SPACE; CHAR_TABLE['\f'] |= MASK_SPACE;
}; }
static class MatchState { static class MatchState {
int matchdepth; /* control for recursive depth (to avoid C stack overflow) */ 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) { for (int i = 0; i < l; ++i) {
byte b = (byte) news.luaByte(i); byte b = (byte) news.luaByte(i);
if (b != L_ESC) { if (b != L_ESC) {
lbuf.append((byte) b); lbuf.append(b);
} else { } else {
++i; // skip ESC ++i; // skip ESC
b = (byte) (i < l? news.luaByte(i): 0); 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) { 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) { switch (nlevels) {
case 0: case 0:
return NONE; return NONE;
@@ -1067,12 +1083,12 @@ public class StringLib extends TwoArgFunction {
res = (cdata & MASK_HEXDIGIT) != 0; res = (cdata & MASK_HEXDIGIT) != 0;
break; break;
case 'z': case 'z':
res = (c == 0); res = c == 0;
break; /* deprecated option */ break; /* deprecated option */
default: default:
return cl == c; return cl == c;
} }
return (lcl == cl)? res: !res; return lcl == cl == res;
} }
boolean matchbracketclass(int c, int poff, int ec) { boolean matchbracketclass(int c, int poff, int ec) {
@@ -1086,7 +1102,7 @@ public class StringLib extends TwoArgFunction {
poff++; poff++;
if (match_class(c, p.luaByte(poff))) if (match_class(c, p.luaByte(poff)))
return sig; return sig;
} else if ((p.luaByte(poff+1) == '-') && (poff+2 < ec)) { } else if (p.luaByte(poff+1) == '-' && poff+2 < ec) {
poff += 2; poff += 2;
if (p.luaByte(poff-2) <= c && c <= p.luaByte(poff)) if (p.luaByte(poff-2) <= c && c <= p.luaByte(poff))
return sig; return sig;
@@ -1147,8 +1163,8 @@ public class StringLib extends TwoArgFunction {
error("missing '[' after '%f' in pattern"); error("missing '[' after '%f' in pattern");
} }
int ep = classend(poffset); int ep = classend(poffset);
int previous = (soffset == 0)? '\0': s.luaByte(soffset-1); int previous = soffset == 0? '\0': s.luaByte(soffset-1);
int next = (soffset == s.length())? '\0': s.luaByte(soffset); int next = soffset == s.length()? '\0': s.luaByte(soffset);
if (matchbracketclass(previous, poffset, ep-1) || !matchbracketclass(next, poffset, ep-1)) if (matchbracketclass(previous, poffset, ep-1) || !matchbracketclass(next, poffset, ep-1))
return -1; return -1;
poffset = ep; poffset = ep;
@@ -1166,23 +1182,23 @@ public class StringLib extends TwoArgFunction {
} }
case '$': case '$':
if (poffset+1 == p.length()) if (poffset+1 == p.length())
return (soffset == s.length())? soffset: -1; return soffset == s.length()? soffset: -1;
} }
int ep = classend(poffset); int ep = classend(poffset);
boolean m = soffset < s.length() && singlematch(s.luaByte(soffset), poffset, ep); 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) { switch (pc) {
case '?': case '?':
int res; int res;
if (m && ((res = match(soffset+1, ep+1)) != -1)) if (m && (res = match(soffset+1, ep+1)) != -1)
return res; return res;
poffset = ep+1; poffset = ep+1;
continue; continue;
case '*': case '*':
return max_expand(soffset, poffset, ep); return max_expand(soffset, poffset, ep);
case '+': case '+':
return (m? max_expand(soffset+1, poffset, ep): -1); return m? max_expand(soffset+1, poffset, ep): -1;
case '-': case '-':
return min_expand(soffset, poffset, ep); return min_expand(soffset, poffset, ep);
default: default:
@@ -1190,7 +1206,6 @@ public class StringLib extends TwoArgFunction {
return -1; return -1;
soffset++; soffset++;
poffset = ep; poffset = ep;
continue;
} }
} }
} finally { } finally {
@@ -1249,7 +1264,7 @@ public class StringLib extends TwoArgFunction {
int match_capture(int soff, int l) { int match_capture(int soff, int l) {
l = check_capture(l); l = check_capture(l);
int len = clen[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; return soff+len;
else else
return -1; return -1;

View File

@@ -10,7 +10,7 @@
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * 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 * Subclass of {@link LibFunction} which implements the lua standard
* {@code table} library. * {@code table} library.
* *
* <p> * <p>
* Typically, this library is included as part of a call to either * 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.jse.JsePlatform#standardGlobals()} or
* {@link org.luaj.vm2.lib.jme.JmePlatform#standardGlobals()} * {@link org.luaj.vm2.lib.jme.JmePlatform#standardGlobals()}
* *
* <pre> * <pre>
* { * {
* &#64;code * &#64;code
@@ -44,7 +44,7 @@ import org.luaj.vm2.Varargs;
* <p> * <p>
* To instantiate and use it directly, link it into your globals table via * To instantiate and use it directly, link it into your globals table via
* {@link LuaValue#load(LuaValue)} using code such as: * {@link LuaValue#load(LuaValue)} using code such as:
* *
* <pre> * <pre>
* { * {
* &#64;code * &#64;code
@@ -58,7 +58,7 @@ import org.luaj.vm2.Varargs;
* <p> * <p>
* This has been implemented to match as closely as possible the behavior in the * This has been implemented to match as closely as possible the behavior in the
* corresponding library in C. * corresponding library in C.
* *
* @see LibFunction * @see LibFunction
* @see org.luaj.vm2.lib.jse.JsePlatform * @see org.luaj.vm2.lib.jse.JsePlatform
* @see org.luaj.vm2.lib.jme.JmePlatform * @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 * containing the library functions, adding that table to the supplied
* environment, adding the table to package.loaded, and returning table as * environment, adding the table to package.loaded, and returning table as
* the return value. * the return value.
* *
* @param modname the module name supplied if this is loaded via 'require'. * @param modname the module name supplied if this is loaded via 'require'.
* @param env the environment to load into, typically a Globals * @param env the environment to load into, typically a Globals
* instance. * instance.
*/ */
@Override
public LuaValue call(LuaValue modname, LuaValue env) { public LuaValue call(LuaValue modname, LuaValue env) {
LuaTable table = new LuaTable(); LuaTable table = new LuaTable();
table.set("concat", new concat()); table.set("concat", new concat());
@@ -93,18 +94,22 @@ public class TableLib extends TwoArgFunction {
// "concat" (table [, sep [, i [, j]]]) -> string // "concat" (table [, sep [, i [, j]]]) -> string
static class concat extends TableLibFunction { static class concat extends TableLibFunction {
@Override
public LuaValue call(LuaValue list) { public LuaValue call(LuaValue list) {
return list.checktable().concat(EMPTYSTRING, 1, list.length()); return list.checktable().concat(EMPTYSTRING, 1, list.length());
} }
@Override
public LuaValue call(LuaValue list, LuaValue sep) { public LuaValue call(LuaValue list, LuaValue sep) {
return list.checktable().concat(sep.checkstring(), 1, list.length()); return list.checktable().concat(sep.checkstring(), 1, list.length());
} }
@Override
public LuaValue call(LuaValue list, LuaValue sep, LuaValue i) { public LuaValue call(LuaValue list, LuaValue sep, LuaValue i) {
return list.checktable().concat(sep.checkstring(), i.checkint(), list.length()); return list.checktable().concat(sep.checkstring(), i.checkint(), list.length());
} }
@Override
public LuaValue call(LuaValue list, LuaValue sep, LuaValue i, LuaValue j) { public LuaValue call(LuaValue list, LuaValue sep, LuaValue i, LuaValue j) {
return list.checktable().concat(sep.checkstring(), i.checkint(), j.checkint()); return list.checktable().concat(sep.checkstring(), i.checkint(), j.checkint());
} }
@@ -112,6 +117,7 @@ public class TableLib extends TwoArgFunction {
// "insert" (table, [pos,] value) // "insert" (table, [pos,] value)
static class insert extends VarArgFunction { static class insert extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) { public Varargs invoke(Varargs args) {
switch (args.narg()) { switch (args.narg()) {
case 2: { case 2: {
@@ -137,6 +143,7 @@ public class TableLib extends TwoArgFunction {
// "pack" (...) -> table // "pack" (...) -> table
static class pack extends VarArgFunction { static class pack extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) { public Varargs invoke(Varargs args) {
LuaValue t = tableOf(args, 1); LuaValue t = tableOf(args, 1);
t.set("n", args.narg()); t.set("n", args.narg());
@@ -146,6 +153,7 @@ public class TableLib extends TwoArgFunction {
// "remove" (table [, pos]) -> removed-ele // "remove" (table [, pos]) -> removed-ele
static class remove extends VarArgFunction { static class remove extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) { public Varargs invoke(Varargs args) {
LuaTable table = args.checktable(1); LuaTable table = args.checktable(1);
int size = table.length(); int size = table.length();
@@ -159,6 +167,7 @@ public class TableLib extends TwoArgFunction {
// "sort" (table [, comp]) // "sort" (table [, comp])
static class sort extends VarArgFunction { static class sort extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) { public Varargs invoke(Varargs args) {
args.checktable(1).sort(args.isnil(2)? NIL: args.checkfunction(2)); args.checktable(1).sort(args.isnil(2)? NIL: args.checkfunction(2));
return NONE; return NONE;
@@ -167,6 +176,7 @@ public class TableLib extends TwoArgFunction {
// "unpack", // (list [,i [,j]]) -> result1, ... // "unpack", // (list [,i [,j]]) -> result1, ...
static class unpack extends VarArgFunction { static class unpack extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) { public Varargs invoke(Varargs args) {
LuaTable t = args.checktable(1); LuaTable t = args.checktable(1);
// do not waste resource for calc rawlen if arg3 is not nil // 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; import org.luaj.vm2.LuaValue;
class TableLibFunction extends LibFunction { class TableLibFunction extends LibFunction {
@Override
public LuaValue call() { public LuaValue call() {
return argerror(1, "table expected, got no value"); 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 * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -41,7 +41,7 @@ import org.luaj.vm2.Varargs;
* <p> * <p>
* See {@link LibFunction} for more information on implementation libraries and * See {@link LibFunction} for more information on implementation libraries and
* library functions. * library functions.
* *
* @see #call(LuaValue,LuaValue,LuaValue) * @see #call(LuaValue,LuaValue,LuaValue)
* @see LibFunction * @see LibFunction
* @see ZeroArgFunction * @see ZeroArgFunction
@@ -51,24 +51,29 @@ import org.luaj.vm2.Varargs;
*/ */
abstract public class ThreeArgFunction extends LibFunction { abstract public class ThreeArgFunction extends LibFunction {
@Override
abstract public LuaValue call(LuaValue arg1, LuaValue arg2, LuaValue arg3); abstract public LuaValue call(LuaValue arg1, LuaValue arg2, LuaValue arg3);
/** Default constructor */ /** Default constructor */
public ThreeArgFunction() { public ThreeArgFunction() {
} }
@Override
public final LuaValue call() { public final LuaValue call() {
return call(NIL, NIL, NIL); return call(NIL, NIL, NIL);
} }
@Override
public final LuaValue call(LuaValue arg) { public final LuaValue call(LuaValue arg) {
return call(arg, NIL, NIL); return call(arg, NIL, NIL);
} }
@Override
public LuaValue call(LuaValue arg1, LuaValue arg2) { public LuaValue call(LuaValue arg1, LuaValue arg2) {
return call(arg1, arg2, NIL); return call(arg1, arg2, NIL);
} }
@Override
public Varargs invoke(Varargs varargs) { public Varargs invoke(Varargs varargs) {
return call(varargs.arg1(), varargs.arg(2), varargs.arg(3)); 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 * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -41,7 +41,7 @@ import org.luaj.vm2.Varargs;
* <p> * <p>
* See {@link LibFunction} for more information on implementation libraries and * See {@link LibFunction} for more information on implementation libraries and
* library functions. * library functions.
* *
* @see #call(LuaValue,LuaValue) * @see #call(LuaValue,LuaValue)
* @see LibFunction * @see LibFunction
* @see ZeroArgFunction * @see ZeroArgFunction
@@ -51,24 +51,29 @@ import org.luaj.vm2.Varargs;
*/ */
abstract public class TwoArgFunction extends LibFunction { abstract public class TwoArgFunction extends LibFunction {
@Override
abstract public LuaValue call(LuaValue arg1, LuaValue arg2); abstract public LuaValue call(LuaValue arg1, LuaValue arg2);
/** Default constructor */ /** Default constructor */
public TwoArgFunction() { public TwoArgFunction() {
} }
@Override
public final LuaValue call() { public final LuaValue call() {
return call(NIL, NIL); return call(NIL, NIL);
} }
@Override
public final LuaValue call(LuaValue arg) { public final LuaValue call(LuaValue arg) {
return call(arg, NIL); return call(arg, NIL);
} }
@Override
public LuaValue call(LuaValue arg1, LuaValue arg2, LuaValue arg3) { public LuaValue call(LuaValue arg1, LuaValue arg2, LuaValue arg3) {
return call(arg1, arg2); return call(arg1, arg2);
} }
@Override
public Varargs invoke(Varargs varargs) { public Varargs invoke(Varargs varargs) {
return call(varargs.arg1(), varargs.arg(2)); 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 * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -40,7 +40,7 @@ import org.luaj.vm2.Varargs;
* <p> * <p>
* See {@link LibFunction} for more information on implementation libraries and * See {@link LibFunction} for more information on implementation libraries and
* library functions. * library functions.
* *
* @see #invoke(Varargs) * @see #invoke(Varargs)
* @see LibFunction * @see LibFunction
* @see ZeroArgFunction * @see ZeroArgFunction
@@ -53,18 +53,22 @@ abstract public class VarArgFunction extends LibFunction {
public VarArgFunction() { public VarArgFunction() {
} }
@Override
public LuaValue call() { public LuaValue call() {
return invoke(NONE).arg1(); return invoke(NONE).arg1();
} }
@Override
public LuaValue call(LuaValue arg) { public LuaValue call(LuaValue arg) {
return invoke(arg).arg1(); return invoke(arg).arg1();
} }
@Override
public LuaValue call(LuaValue arg1, LuaValue arg2) { public LuaValue call(LuaValue arg1, LuaValue arg2) {
return invoke(varargsOf(arg1, arg2)).arg1(); return invoke(varargsOf(arg1, arg2)).arg1();
} }
@Override
public LuaValue call(LuaValue arg1, LuaValue arg2, LuaValue arg3) { public LuaValue call(LuaValue arg1, LuaValue arg2, LuaValue arg3) {
return invoke(varargsOf(arg1, arg2, arg3)).arg1(); 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. * Subclass responsibility. May not have expected behavior for tail calls.
* Should not be used if: - function has a possibility of returning a * Should not be used if: - function has a possibility of returning a
* TailcallVarargs * TailcallVarargs
* *
* @param args the arguments to the function call. * @param args the arguments to the function call.
*/ */
@Override
public Varargs invoke(Varargs args) { public Varargs invoke(Varargs args) {
return onInvoke(args).eval(); return onInvoke(args).eval();
} }
@Override
public Varargs onInvoke(Varargs args) { public Varargs onInvoke(Varargs args) {
return invoke(args); return invoke(args);
} }

View File

@@ -10,7 +10,7 @@
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -38,7 +38,7 @@ import org.luaj.vm2.Varargs;
* <p> * <p>
* See {@link LibFunction} for more information on implementation libraries and * See {@link LibFunction} for more information on implementation libraries and
* library functions. * library functions.
* *
* @see #call() * @see #call()
* @see LibFunction * @see LibFunction
* @see OneArgFunction * @see OneArgFunction
@@ -48,24 +48,29 @@ import org.luaj.vm2.Varargs;
*/ */
abstract public class ZeroArgFunction extends LibFunction { abstract public class ZeroArgFunction extends LibFunction {
@Override
abstract public LuaValue call(); abstract public LuaValue call();
/** Default constructor */ /** Default constructor */
public ZeroArgFunction() { public ZeroArgFunction() {
} }
@Override
public LuaValue call(LuaValue arg) { public LuaValue call(LuaValue arg) {
return call(); return call();
} }
@Override
public LuaValue call(LuaValue arg1, LuaValue arg2) { public LuaValue call(LuaValue arg1, LuaValue arg2) {
return call(); return call();
} }
@Override
public LuaValue call(LuaValue arg1, LuaValue arg2, LuaValue arg3) { public LuaValue call(LuaValue arg1, LuaValue arg2, LuaValue arg3) {
return call(); return call();
} }
@Override
public Varargs invoke(Varargs varargs) { public Varargs invoke(Varargs varargs) {
return call(); return call();
} }

View File

@@ -10,7 +10,7 @@
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -43,7 +43,7 @@ import org.luaj.vm2.lib.LibFunction;
* <p> * <p>
* Typically, this library is included as part of a call to * Typically, this library is included as part of a call to
* {@link org.luaj.vm2.lib.jme.JmePlatform#standardGlobals()} * {@link org.luaj.vm2.lib.jme.JmePlatform#standardGlobals()}
* *
* <pre> * <pre>
* { * {
* &#64;code * &#64;code
@@ -55,7 +55,7 @@ import org.luaj.vm2.lib.LibFunction;
* For special cases where the smallest possible footprint is desired, a minimal * For special cases where the smallest possible footprint is desired, a minimal
* set of libraries could be loaded directly via {@link Globals#load(LuaValue)} * set of libraries could be loaded directly via {@link Globals#load(LuaValue)}
* using code such as: * using code such as:
* *
* <pre> * <pre>
* { * {
* &#64;code * &#64;code
@@ -72,7 +72,7 @@ import org.luaj.vm2.lib.LibFunction;
* <p> * <p>
* This has been implemented to match as closely as possible the behavior in the * This has been implemented to match as closely as possible the behavior in the
* corresponding library in C. * corresponding library in C.
* *
* @see LibFunction * @see LibFunction
* @see org.luaj.vm2.lib.jse.JsePlatform * @see org.luaj.vm2.lib.jse.JsePlatform
* @see org.luaj.vm2.lib.jme.JmePlatform * @see org.luaj.vm2.lib.jme.JmePlatform
@@ -83,25 +83,28 @@ import org.luaj.vm2.lib.LibFunction;
*/ */
public class JmeIoLib extends IoLib { public class JmeIoLib extends IoLib {
@Override
protected File wrapStdin() throws IOException { protected File wrapStdin() throws IOException {
return new FileImpl(globals.STDIN); return new FileImpl(globals.STDIN);
} }
@Override
protected File wrapStdout() throws IOException { protected File wrapStdout() throws IOException {
return new FileImpl(globals.STDOUT); return new FileImpl(globals.STDOUT);
} }
@Override
protected File wrapStderr() throws IOException { protected File wrapStderr() throws IOException {
return new FileImpl(globals.STDERR); return new FileImpl(globals.STDERR);
} }
@Override
protected File openFile(String filename, boolean readMode, boolean appendMode, boolean updateMode, protected File openFile(String filename, boolean readMode, boolean appendMode, boolean updateMode,
boolean binaryMode) throws IOException { boolean binaryMode) throws IOException {
String url = "file:///" + filename; String url = "file:///" + filename;
int mode = readMode? Connector.READ: Connector.READ_WRITE; int mode = readMode? Connector.READ: Connector.READ_WRITE;
StreamConnection conn = (StreamConnection) Connector.open(url, mode); 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 ) { if ( appendMode ) {
f.seek("end",0); f.seek("end",0);
@@ -110,18 +113,21 @@ public class JmeIoLib extends IoLib {
conn.truncate(0); 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 { private static void notimplemented() throws IOException {
throw new IOException("not implemented"); throw new IOException("not implemented");
} }
@Override
protected File openProgram(String prog, String mode) throws IOException { protected File openProgram(String prog, String mode) throws IOException {
notimplemented(); notimplemented();
return null; return null;
} }
@Override
protected File tmpFile() throws IOException { protected File tmpFile() throws IOException {
notimplemented(); notimplemented();
return null; return null;
@@ -149,14 +155,17 @@ public class JmeIoLib extends IoLib {
this(null, null, o); this(null, null, o);
} }
@Override
public String tojstring() { public String tojstring() {
return "file (" + this.hashCode() + ")"; return "file (" + this.hashCode() + ")";
} }
@Override
public boolean isstdfile() { public boolean isstdfile() {
return conn == null; return conn == null;
} }
@Override
public void close() throws IOException { public void close() throws IOException {
closed = true; closed = true;
if (conn != null) { if (conn != null) {
@@ -164,11 +173,13 @@ public class JmeIoLib extends IoLib {
} }
} }
@Override
public void flush() throws IOException { public void flush() throws IOException {
if (os != null) if (os != null)
os.flush(); os.flush();
} }
@Override
public void write(LuaString s) throws IOException { public void write(LuaString s) throws IOException {
if (os != null) if (os != null)
os.write(s.m_bytes, s.m_offset, s.m_length); os.write(s.m_bytes, s.m_offset, s.m_length);
@@ -178,10 +189,12 @@ public class JmeIoLib extends IoLib {
flush(); flush();
} }
@Override
public boolean isclosed() { public boolean isclosed() {
return closed; return closed;
} }
@Override
public int seek(String option, int pos) throws IOException { public int seek(String option, int pos) throws IOException {
/* /*
if ( conn != null ) { if ( conn != null ) {
@@ -201,23 +214,27 @@ public class JmeIoLib extends IoLib {
return 0; return 0;
} }
@Override
public void setvbuf(String mode, int size) { public void setvbuf(String mode, int size) {
nobuffer = "no".equals(mode); nobuffer = "no".equals(mode);
} }
// get length remaining to read // get length remaining to read
@Override
public int remaining() throws IOException { public int remaining() throws IOException {
return -1; return -1;
} }
// peek ahead one character // peek ahead one character
@Override
public int peek() throws IOException { public int peek() throws IOException {
if (lookahead < 0) if (lookahead < 0)
lookahead = is.read(); lookahead = is.read();
return lookahead; 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 { public int read() throws IOException {
if (lookahead >= 0) { if (lookahead >= 0) {
int c = lookahead; int c = lookahead;
@@ -231,6 +248,7 @@ public class JmeIoLib extends IoLib {
} }
// return number of bytes read if positive, -1 if eof, throws IOException // return number of bytes read if positive, -1 if eof, throws IOException
@Override
public int read(byte[] bytes, int offset, int length) throws IOException { public int read(byte[] bytes, int offset, int length) throws IOException {
int n, i = 0; int n, i = 0;
if (is != null) { if (is != null) {
@@ -242,7 +260,7 @@ public class JmeIoLib extends IoLib {
for (; i < length;) { for (; i < length;) {
n = is.read(bytes, offset+i, length-i); n = is.read(bytes, offset+i, length-i);
if (n < 0) if (n < 0)
return (i > 0? i: -1); return i > 0? i: -1;
i += n; i += n;
} }
} else { } else {

View File

@@ -10,7 +10,7 @@
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * 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.Globals;
import org.luaj.vm2.LoadState; 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.compiler.LuaC;
import org.luaj.vm2.lib.BaseLib; import org.luaj.vm2.lib.BaseLib;
import org.luaj.vm2.lib.Bit32Lib; import org.luaj.vm2.lib.Bit32Lib;
@@ -60,7 +58,7 @@ import org.luaj.vm2.lib.TableLib;
* {@link #standardGlobals()} or debug globals using {@link #debugGlobals()} * {@link #standardGlobals()} or debug globals using {@link #debugGlobals()}
* <p> * <p>
* A simple example of initializing globals and using them from Java is: * A simple example of initializing globals and using them from Java is:
* *
* <pre> * <pre>
* { * {
* &#64;code * &#64;code
@@ -70,7 +68,7 @@ import org.luaj.vm2.lib.TableLib;
* </pre> * </pre>
* <p> * <p>
* Once globals are created, a simple way to load and run a script is: * Once globals are created, a simple way to load and run a script is:
* *
* <pre> * <pre>
* {@code * {@code
* LoadState.load( getClass().getResourceAsStream("main.lua"), "main.lua", globals ).call(); * LoadState.load( getClass().getResourceAsStream("main.lua"), "main.lua", globals ).call();
@@ -78,13 +76,13 @@ import org.luaj.vm2.lib.TableLib;
* </pre> * </pre>
* <p> * <p>
* although {@code require} could also be used: * although {@code require} could also be used:
* *
* <pre> * <pre>
* {@code * {@code
* globals.get("require").call(LuaValue.valueOf("main")); * globals.get("require").call(LuaValue.valueOf("main"));
* } * }
* </pre> * </pre>
* *
* For this to succeed, the file "main.lua" must be a resource in the class * 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 * path. See {@link BaseLib} for details on finding scripts using
* {@link ResourceFinder}. * {@link ResourceFinder}.
@@ -111,7 +109,7 @@ import org.luaj.vm2.lib.TableLib;
* <p> * <p>
* <p> * <p>
* The class ensures that initialization is done in the correct order. * The class ensures that initialization is done in the correct order.
* *
* @see Globals * @see Globals
* @see org.luaj.vm2.lib.jse.JsePlatform * @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. * Create a standard set of globals for JME including all the libraries.
* *
* @return Table of globals initialized with the standard JME libraries * @return Table of globals initialized with the standard JME libraries
* @see #debugGlobals() * @see #debugGlobals()
* @see org.luaj.vm2.lib.jse.JsePlatform * @see org.luaj.vm2.lib.jse.JsePlatform
@@ -143,7 +141,7 @@ public class JmePlatform {
/** /**
* Create standard globals including the {@link DebugLib} library. * Create standard globals including the {@link DebugLib} library.
* *
* @return Table of globals initialized with the standard JSE and debug * @return Table of globals initialized with the standard JSE and debug
* libraries * libraries
* @see #standardGlobals() * @see #standardGlobals()

View File

@@ -11,7 +11,7 @@
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * 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 { public static void main(String[] args) throws IOException {
// process args // process args
boolean interactive = (args.length == 0); boolean interactive = args.length == 0;
boolean versioninfo = false; boolean versioninfo = false;
boolean processing = true; boolean processing = true;
boolean nodebug = false; boolean nodebug = false;

View File

@@ -11,7 +11,7 @@
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -128,10 +128,8 @@ public class luac {
System.out.println(version); System.out.println(version);
// open output file // open output file
OutputStream fos = new FileOutputStream(output);
// process input files // process input files
try { try (OutputStream fos = new FileOutputStream(output)) {
Globals globals = JsePlatform.standardGlobals(); Globals globals = JsePlatform.standardGlobals();
processing = true; processing = true;
for (int i = 0; i < args.length; i++) { for (int i = 0; i < args.length; i++) {
@@ -152,8 +150,6 @@ public class luac {
} }
} }
} }
} finally {
fos.close();
} }
} catch (IOException ioe) { } catch (IOException ioe) {

View File

@@ -11,7 +11,7 @@
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -55,16 +55,16 @@ public class luajc {
System.exit(-1); System.exit(-1);
} }
private String srcdir = "."; private String srcdir = ".";
private String destdir = "."; private String destdir = ".";
private boolean genmain = false; private boolean genmain = false;
private boolean recurse = false; private boolean recurse = false;
private boolean verbose = false; private boolean verbose = false;
private boolean loadclasses = false; private boolean loadclasses = false;
private String encoding = null; private String encoding = null;
private String pkgprefix = null; private String pkgprefix = null;
private List files = new ArrayList(); private final List files = new ArrayList();
private Globals globals; private final Globals globals;
public static void main(String[] args) throws IOException { public static void main(String[] args) throws IOException {
new luajc(args); new luajc(args);
@@ -136,8 +136,8 @@ public class luajc {
} }
// collect up files to process // collect up files to process
for (int i = 0; i < seeds.size(); i++) for (Object seed : seeds)
collectFiles(srcdir + "/" + seeds.get(i)); collectFiles(srcdir + "/" + seed);
// check for at least one file // check for at least one file
if (files.size() <= 0) { if (files.size() <= 0) {
@@ -147,8 +147,8 @@ public class luajc {
// process input files // process input files
globals = JsePlatform.standardGlobals(); globals = JsePlatform.standardGlobals();
for (int i = 0, n = files.size(); i < n; i++) for (Object file : files)
processFile((InputFile) files.get(i)); processFile((InputFile) file);
} }
private void collectFiles(String path) { private void collectFiles(String path) {
@@ -164,14 +164,14 @@ public class luajc {
private void scandir(File dir, String javapackage) { private void scandir(File dir, String javapackage) {
File[] f = dir.listFiles(); File[] f = dir.listFiles();
for (int i = 0; i < f.length; i++) for (File element : f)
scanfile(dir, f[i], javapackage); scanfile(dir, element, javapackage);
} }
private void scanfile(File dir, File f, String javapackage) { private void scanfile(File dir, File f, String javapackage) {
if (f.exists()) { if (f.exists()) {
if (f.isDirectory() && recurse) 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")) else if (f.isFile() && f.getName().endsWith(".lua"))
files.add(new InputFile(dir, f, javapackage)); files.add(new InputFile(dir, f, javapackage));
} }
@@ -184,6 +184,7 @@ public class luajc {
this.t = t; this.t = t;
} }
@Override
public Class findClass(String classname) throws ClassNotFoundException { public Class findClass(String classname) throws ClassNotFoundException {
byte[] bytes = (byte[]) t.get(classname); byte[] bytes = (byte[]) t.get(classname);
if (bytes != null) if (bytes != null)

View File

@@ -10,7 +10,7 @@
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * 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 class Block extends Stat {
public List<Stat> stats = new ArrayList<Stat>(); public List<Stat> stats = new ArrayList<>();
public NameScope scope; public NameScope scope;
public void add(Stat s) { public void add(Stat s) {
@@ -35,6 +35,7 @@ public class Block extends Stat {
stats.add(s); stats.add(s);
} }
@Override
public void accept(Visitor visitor) { public void accept(Visitor visitor) {
visitor.visit(this); visitor.visit(this);
} }

View File

@@ -10,7 +10,7 @@
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * 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 * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * 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 // TODO: constant folding
if (lhs instanceof BinopExp) { if (lhs instanceof BinopExp) {
BinopExp b = (BinopExp) lhs; 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)); return binaryexp(b.lhs, b.op, binaryexp(b.rhs, op, rhs));
} }
if (rhs instanceof BinopExp) { if (rhs instanceof BinopExp) {
BinopExp b = (BinopExp) rhs; 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 binaryexp(binaryexp(lhs, op, b.lhs), b.op, b.rhs);
} }
return new BinopExp(lhs, op, rhs); return new BinopExp(lhs, op, rhs);
@@ -163,16 +163,19 @@ abstract public class Exp extends SyntaxElement {
} }
abstract public static class PrimaryExp extends Exp { abstract public static class PrimaryExp extends Exp {
@Override
public boolean isvarexp() { public boolean isvarexp() {
return false; return false;
} }
@Override
public boolean isfunccall() { public boolean isfunccall() {
return false; return false;
} }
} }
abstract public static class VarExp extends PrimaryExp { abstract public static class VarExp extends PrimaryExp {
@Override
public boolean isvarexp() { public boolean isvarexp() {
return true; return true;
} }
@@ -188,10 +191,12 @@ abstract public class Exp extends SyntaxElement {
this.name = new Name(name); this.name = new Name(name);
} }
@Override
public void markHasAssignment() { public void markHasAssignment() {
name.variable.hasassignments = true; name.variable.hasassignments = true;
} }
@Override
public void accept(Visitor visitor) { public void accept(Visitor visitor) {
visitor.visit(this); visitor.visit(this);
} }
@@ -204,6 +209,7 @@ abstract public class Exp extends SyntaxElement {
this.exp = exp; this.exp = exp;
} }
@Override
public void accept(Visitor visitor) { public void accept(Visitor visitor) {
visitor.visit(this); visitor.visit(this);
} }
@@ -218,6 +224,7 @@ abstract public class Exp extends SyntaxElement {
this.name = new Name(name); this.name = new Name(name);
} }
@Override
public void accept(Visitor visitor) { public void accept(Visitor visitor) {
visitor.visit(this); visitor.visit(this);
} }
@@ -232,6 +239,7 @@ abstract public class Exp extends SyntaxElement {
this.exp = exp; this.exp = exp;
} }
@Override
public void accept(Visitor visitor) { public void accept(Visitor visitor) {
visitor.visit(this); visitor.visit(this);
} }
@@ -246,14 +254,17 @@ abstract public class Exp extends SyntaxElement {
this.args = args; this.args = args;
} }
@Override
public boolean isfunccall() { public boolean isfunccall() {
return true; return true;
} }
@Override
public void accept(Visitor visitor) { public void accept(Visitor visitor) {
visitor.visit(this); visitor.visit(this);
} }
@Override
public boolean isvarargexp() { public boolean isvarargexp() {
return true; return true;
} }
@@ -267,10 +278,12 @@ abstract public class Exp extends SyntaxElement {
this.name = new String(name); this.name = new String(name);
} }
@Override
public boolean isfunccall() { public boolean isfunccall() {
return true; return true;
} }
@Override
public void accept(Visitor visitor) { public void accept(Visitor visitor) {
visitor.visit(this); visitor.visit(this);
} }
@@ -283,6 +296,7 @@ abstract public class Exp extends SyntaxElement {
this.value = value; this.value = value;
} }
@Override
public void accept(Visitor visitor) { public void accept(Visitor visitor) {
visitor.visit(this); visitor.visit(this);
} }
@@ -290,10 +304,12 @@ abstract public class Exp extends SyntaxElement {
public static class VarargsExp extends Exp { public static class VarargsExp extends Exp {
@Override
public void accept(Visitor visitor) { public void accept(Visitor visitor) {
visitor.visit(this); visitor.visit(this);
} }
@Override
public boolean isvarargexp() { public boolean isvarargexp() {
return true; return true;
} }
@@ -308,6 +324,7 @@ abstract public class Exp extends SyntaxElement {
this.rhs = rhs; this.rhs = rhs;
} }
@Override
public void accept(Visitor visitor) { public void accept(Visitor visitor) {
visitor.visit(this); visitor.visit(this);
} }
@@ -323,6 +340,7 @@ abstract public class Exp extends SyntaxElement {
this.rhs = rhs; this.rhs = rhs;
} }
@Override
public void accept(Visitor visitor) { public void accept(Visitor visitor) {
visitor.visit(this); visitor.visit(this);
} }
@@ -335,6 +353,7 @@ abstract public class Exp extends SyntaxElement {
this.body = funcbody; this.body = funcbody;
} }
@Override
public void accept(Visitor visitor) { public void accept(Visitor visitor) {
visitor.visit(this); visitor.visit(this);
} }

View File

@@ -10,7 +10,7 @@
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * 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) { public FuncArgs(LuaString string) {
this.exps = new ArrayList<Exp>(); this.exps = new ArrayList<>();
this.exps.add(Exp.constant(string)); this.exps.add(Exp.constant(string));
} }
public FuncArgs(TableConstructor table) { public FuncArgs(TableConstructor table) {
this.exps = new ArrayList<Exp>(); this.exps = new ArrayList<>();
this.exps.add(table); this.exps.add(table);
} }

View File

@@ -10,7 +10,7 @@
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * 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 * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * 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) { public void adddot(String dot) {
if (dots == null) if (dots == null)
dots = new ArrayList<String>(); dots = new ArrayList<>();
dots.add(dot); dots.add(dot);
} }

View File

@@ -10,7 +10,7 @@
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * 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; scope = scope.outerScope;
} }
@Override
public void visit(NameScope scope) { public void visit(NameScope scope) {
} }
@Override
public void visit(Block block) { public void visit(Block block) {
pushScope(); pushScope();
block.scope = scope; block.scope = scope;
@@ -40,6 +42,7 @@ public class NameResolver extends Visitor {
popScope(); popScope();
} }
@Override
public void visit(FuncBody body) { public void visit(FuncBody body) {
pushScope(); pushScope();
scope.functionNestingCount++; scope.functionNestingCount++;
@@ -48,11 +51,13 @@ public class NameResolver extends Visitor {
popScope(); popScope();
} }
@Override
public void visit(LocalFuncDef stat) { public void visit(LocalFuncDef stat) {
defineLocalVar(stat.name); defineLocalVar(stat.name);
super.visit(stat); super.visit(stat);
} }
@Override
public void visit(NumericFor stat) { public void visit(NumericFor stat) {
pushScope(); pushScope();
stat.scope = scope; stat.scope = scope;
@@ -61,6 +66,7 @@ public class NameResolver extends Visitor {
popScope(); popScope();
} }
@Override
public void visit(GenericFor stat) { public void visit(GenericFor stat) {
pushScope(); pushScope();
stat.scope = scope; stat.scope = scope;
@@ -69,39 +75,44 @@ public class NameResolver extends Visitor {
popScope(); popScope();
} }
@Override
public void visit(NameExp exp) { public void visit(NameExp exp) {
exp.name.variable = resolveNameReference(exp.name); exp.name.variable = resolveNameReference(exp.name);
super.visit(exp); super.visit(exp);
} }
@Override
public void visit(FuncDef stat) { public void visit(FuncDef stat) {
stat.name.name.variable = resolveNameReference(stat.name.name); stat.name.name.variable = resolveNameReference(stat.name.name);
stat.name.name.variable.hasassignments = true; stat.name.name.variable.hasassignments = true;
super.visit(stat); super.visit(stat);
} }
@Override
public void visit(Assign stat) { public void visit(Assign stat) {
super.visit(stat); super.visit(stat);
for (int i = 0, n = stat.vars.size(); i < n; i++) { for (VarExp element : stat.vars) {
VarExp v = (VarExp) stat.vars.get(i); VarExp v = element;
v.markHasAssignment(); v.markHasAssignment();
} }
} }
@Override
public void visit(LocalAssign stat) { public void visit(LocalAssign stat) {
visitExps(stat.values); visitExps(stat.values);
defineLocalVars(stat.names); defineLocalVars(stat.names);
int n = stat.names.size(); int n = stat.names.size();
int m = stat.values != null? stat.values.size(): 0; 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++) for (int i = 0; i < n && i < (isvarlist? m-1: m); i++)
if (stat.values.get(i) instanceof Constant) 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) if (!isvarlist)
for (int i = m; i < n; i++) 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) { public void visit(ParList pars) {
if (pars.names != null) if (pars.names != null)
defineLocalVars(pars.names); defineLocalVars(pars.names);
@@ -111,8 +122,8 @@ public class NameResolver extends Visitor {
} }
protected void defineLocalVars(List<Name> names) { protected void defineLocalVars(List<Name> names) {
for (int i = 0, n = names.size(); i < n; i++) for (Name name : names)
defineLocalVar((Name) names.get(i)); defineLocalVar(name);
} }
protected void defineLocalVar(Name name) { protected void defineLocalVar(Name name) {

View File

@@ -10,7 +10,7 @@
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -28,16 +28,16 @@ import java.util.Set;
public class NameScope { public class NameScope {
private static final Set<String> LUA_KEYWORDS = new HashSet<String>(); private static final Set<String> LUA_KEYWORDS = new HashSet<>();
static { static {
String[] k = new String[] { "and", "break", "do", "else", "elseif", "end", "false", "for", "function", "if", String[] k = { "and", "break", "do", "else", "elseif", "end", "false", "for", "function", "if", "in", "local",
"in", "local", "nil", "not", "or", "repeat", "return", "then", "true", "until", "while" }; "nil", "not", "or", "repeat", "return", "then", "true", "until", "while" };
for (int i = 0; i < k.length; i++) for (String element : k)
LUA_KEYWORDS.add(k[i]); 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; public final NameScope outerScope;
@@ -63,7 +63,7 @@ public class NameScope {
validateIsNotKeyword(name); validateIsNotKeyword(name);
for (NameScope n = this; n != null; n = n.outerScope) for (NameScope n = this; n != null; n = n.outerScope)
if (n.namedVariables.containsKey(name)) if (n.namedVariables.containsKey(name))
return (Variable) n.namedVariables.get(name); return n.namedVariables.get(name);
Variable value = new Variable(name); Variable value = new Variable(name);
this.namedVariables.put(name, value); this.namedVariables.put(name, value);
return value; return value;

View File

@@ -10,7 +10,7 @@
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -25,7 +25,7 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
public class ParList extends SyntaxElement { 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 static final ParList EMPTY_PARLIST = new ParList(EMPTY_NAMELIST, false);
public final List<Name> names; public final List<Name> names;

View File

@@ -10,7 +10,7 @@
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * 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; this.name = name;
} }
@Override
public void accept(Visitor visitor) { public void accept(Visitor visitor) {
visitor.visit(this); visitor.visit(this);
} }
@@ -108,6 +109,7 @@ abstract public class Stat extends SyntaxElement {
this.name = name; this.name = name;
} }
@Override
public void accept(Visitor visitor) { public void accept(Visitor visitor) {
visitor.visit(this); visitor.visit(this);
} }
@@ -122,6 +124,7 @@ abstract public class Stat extends SyntaxElement {
this.exps = exps; this.exps = exps;
} }
@Override
public void accept(Visitor visitor) { public void accept(Visitor visitor) {
visitor.visit(this); visitor.visit(this);
} }
@@ -137,6 +140,7 @@ abstract public class Stat extends SyntaxElement {
this.block = block; this.block = block;
} }
@Override
public void accept(Visitor visitor) { public void accept(Visitor visitor) {
visitor.visit(this); visitor.visit(this);
} }
@@ -151,12 +155,14 @@ abstract public class Stat extends SyntaxElement {
this.exp = exp; this.exp = exp;
} }
@Override
public void accept(Visitor visitor) { public void accept(Visitor visitor) {
visitor.visit(this); visitor.visit(this);
} }
} }
public static class Break extends Stat { public static class Break extends Stat {
@Override
public void accept(Visitor visitor) { public void accept(Visitor visitor) {
visitor.visit(this); visitor.visit(this);
} }
@@ -169,13 +175,14 @@ abstract public class Stat extends SyntaxElement {
this.values = values; this.values = values;
} }
@Override
public void accept(Visitor visitor) { public void accept(Visitor visitor) {
visitor.visit(this); visitor.visit(this);
} }
public int nreturns() { public int nreturns() {
int n = values != null? values.size(): 0; 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; n = -1;
return n; return n;
} }
@@ -188,6 +195,7 @@ abstract public class Stat extends SyntaxElement {
this.funccall = funccall; this.funccall = funccall;
} }
@Override
public void accept(Visitor visitor) { public void accept(Visitor visitor) {
visitor.visit(this); visitor.visit(this);
} }
@@ -202,6 +210,7 @@ abstract public class Stat extends SyntaxElement {
this.body = body; this.body = body;
} }
@Override
public void accept(Visitor visitor) { public void accept(Visitor visitor) {
visitor.visit(this); visitor.visit(this);
} }
@@ -216,6 +225,7 @@ abstract public class Stat extends SyntaxElement {
this.body = body; this.body = body;
} }
@Override
public void accept(Visitor visitor) { public void accept(Visitor visitor) {
visitor.visit(this); visitor.visit(this);
} }
@@ -233,6 +243,7 @@ abstract public class Stat extends SyntaxElement {
this.block = block; this.block = block;
} }
@Override
public void accept(Visitor visitor) { public void accept(Visitor visitor) {
visitor.visit(this); visitor.visit(this);
} }
@@ -252,6 +263,7 @@ abstract public class Stat extends SyntaxElement {
this.block = block; this.block = block;
} }
@Override
public void accept(Visitor visitor) { public void accept(Visitor visitor) {
visitor.visit(this); visitor.visit(this);
} }
@@ -266,6 +278,7 @@ abstract public class Stat extends SyntaxElement {
this.values = values; this.values = values;
} }
@Override
public void accept(Visitor visitor) { public void accept(Visitor visitor) {
visitor.visit(this); visitor.visit(this);
} }
@@ -286,6 +299,7 @@ abstract public class Stat extends SyntaxElement {
this.elseblock = elseblock; this.elseblock = elseblock;
} }
@Override
public void accept(Visitor visitor) { public void accept(Visitor visitor) {
visitor.visit(this); visitor.visit(this);
} }

View File

@@ -10,7 +10,7 @@
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -74,9 +74,9 @@ public class Str {
case '7': case '7':
case '8': case '8':
case '9': 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++) 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); baos.write((byte) d);
--i; --i;
continue; continue;

View File

@@ -10,7 +10,7 @@
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * 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 * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * 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 class TableConstructor extends Exp {
public List<TableField> fields; public List<TableField> fields;
@Override
public void accept(Visitor visitor) { public void accept(Visitor visitor) {
visitor.visit(this); visitor.visit(this);
} }

View File

@@ -10,7 +10,7 @@
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * 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 * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * 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 * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * 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 { abstract public class Visitor {
public void visit(Chunk chunk) { public void visit(Chunk chunk) {
chunk.block.accept(this); chunk.block.accept(this);
}; }
public void visit(Block block) { public void visit(Block block) {
visit(block.scope); visit(block.scope);
if (block.stats != null) if (block.stats != null)
for (int i = 0, n = block.stats.size(); i < n; i++) for (Stat element : block.stats)
((Stat) block.stats.get(i)).accept(this); element.accept(this);
}; }
public void visit(Stat.Assign stat) { public void visit(Stat.Assign stat) {
visitVars(stat.vars); visitVars(stat.vars);
@@ -65,8 +65,8 @@ abstract public class Visitor {
stat.ifblock.accept(this); stat.ifblock.accept(this);
if (stat.elseifblocks != null) if (stat.elseifblocks != null)
for (int i = 0, n = stat.elseifblocks.size(); i < n; i++) { for (int i = 0, n = stat.elseifblocks.size(); i < n; i++) {
((Exp) stat.elseifexps.get(i)).accept(this); stat.elseifexps.get(i).accept(this);
((Block) stat.elseifblocks.get(i)).accept(this); stat.elseifblocks.get(i).accept(this);
} }
if (stat.elseblock != null) if (stat.elseblock != null)
visit(stat.elseblock); visit(stat.elseblock);
@@ -178,26 +178,26 @@ abstract public class Visitor {
public void visit(TableConstructor table) { public void visit(TableConstructor table) {
if (table.fields != null) if (table.fields != null)
for (int i = 0, n = table.fields.size(); i < n; i++) for (TableField element : table.fields)
((TableField) table.fields.get(i)).accept(this); element.accept(this);
} }
public void visitVars(List<VarExp> vars) { public void visitVars(List<VarExp> vars) {
if (vars != null) if (vars != null)
for (int i = 0, n = vars.size(); i < n; i++) for (VarExp var : vars)
((Exp.VarExp) vars.get(i)).accept(this); var.accept(this);
} }
public void visitExps(List<Exp> exps) { public void visitExps(List<Exp> exps) {
if (exps != null) if (exps != null)
for (int i = 0, n = exps.size(); i < n; i++) for (Exp exp : exps)
((Exp) exps.get(i)).accept(this); exp.accept(this);
} }
public void visitNames(List<Name> names) { public void visitNames(List<Name> names) {
if (names != null) if (names != null)
for (int i = 0, n = names.size(); i < n; i++) for (Name name : names)
visit((Name) names.get(i)); visit(name);
} }
public void visit(Name name) { public void visit(Name name) {

View File

@@ -10,7 +10,7 @@
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * 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 * The method {@link CoerceJavaToLua#coerce(Object)} looks as the type and
* dimesioning of the argument and tries to guess the best fit for corrsponding * dimesioning of the argument and tries to guess the best fit for corrsponding
* lua scalar, table, or table of tables. * lua scalar, table, or table of tables.
* *
* @see CoerceJavaToLua#coerce(Object) * @see CoerceJavaToLua#coerce(Object)
* @see org.luaj.vm2.lib.jse.LuajavaLib * @see org.luaj.vm2.lib.jse.LuajavaLib
*/ */
public class CoerceJavaToLua { public class CoerceJavaToLua {
static interface Coercion { interface Coercion {
public LuaValue coerce(Object javaValue); LuaValue coerce(Object javaValue);
}; }
private static final class BoolCoercion implements Coercion { private static final class BoolCoercion implements Coercion {
@Override
public LuaValue coerce(Object javaValue) { public LuaValue coerce(Object javaValue) {
Boolean b = (Boolean) javaValue; Boolean b = (Boolean) javaValue;
return b.booleanValue()? LuaValue.TRUE: LuaValue.FALSE; return b.booleanValue()? LuaValue.TRUE: LuaValue.FALSE;
@@ -76,6 +77,7 @@ public class CoerceJavaToLua {
} }
private static final class IntCoercion implements Coercion { private static final class IntCoercion implements Coercion {
@Override
public LuaValue coerce(Object javaValue) { public LuaValue coerce(Object javaValue) {
Number n = (Number) javaValue; Number n = (Number) javaValue;
return LuaInteger.valueOf(n.intValue()); return LuaInteger.valueOf(n.intValue());
@@ -83,6 +85,7 @@ public class CoerceJavaToLua {
} }
private static final class CharCoercion implements Coercion { private static final class CharCoercion implements Coercion {
@Override
public LuaValue coerce(Object javaValue) { public LuaValue coerce(Object javaValue) {
Character c = (Character) javaValue; Character c = (Character) javaValue;
return LuaInteger.valueOf(c.charValue()); return LuaInteger.valueOf(c.charValue());
@@ -90,6 +93,7 @@ public class CoerceJavaToLua {
} }
private static final class DoubleCoercion implements Coercion { private static final class DoubleCoercion implements Coercion {
@Override
public LuaValue coerce(Object javaValue) { public LuaValue coerce(Object javaValue) {
Number n = (Number) javaValue; Number n = (Number) javaValue;
return LuaDouble.valueOf(n.doubleValue()); return LuaDouble.valueOf(n.doubleValue());
@@ -97,37 +101,43 @@ public class CoerceJavaToLua {
} }
private static final class StringCoercion implements Coercion { private static final class StringCoercion implements Coercion {
@Override
public LuaValue coerce(Object javaValue) { public LuaValue coerce(Object javaValue) {
return LuaString.valueOf(javaValue.toString()); return LuaString.valueOf(javaValue.toString());
} }
} }
private static final class BytesCoercion implements Coercion { private static final class BytesCoercion implements Coercion {
@Override
public LuaValue coerce(Object javaValue) { public LuaValue coerce(Object javaValue) {
return LuaValue.valueOf((byte[]) javaValue); return LuaValue.valueOf((byte[]) javaValue);
} }
} }
private static final class ClassCoercion implements Coercion { private static final class ClassCoercion implements Coercion {
@Override
public LuaValue coerce(Object javaValue) { public LuaValue coerce(Object javaValue) {
return JavaClass.forClass((Class) javaValue); return JavaClass.forClass((Class) javaValue);
} }
} }
private static final class InstanceCoercion implements Coercion { private static final class InstanceCoercion implements Coercion {
@Override
public LuaValue coerce(Object javaValue) { public LuaValue coerce(Object javaValue) {
return new JavaInstance(javaValue); return new JavaInstance(javaValue);
} }
} }
private static final class ArrayCoercion implements Coercion { private static final class ArrayCoercion implements Coercion {
@Override
public LuaValue coerce(Object javaValue) { public LuaValue coerce(Object javaValue) {
// should be userdata? // should be userdata?
return new JavaArray(javaValue); return new JavaArray(javaValue);
} }
} }
private static final class LuaCoercion implements Coercion { private static final class LuaCoercion implements Coercion {
@Override
public LuaValue coerce(Object javaValue) { public LuaValue coerce(Object javaValue) {
return (LuaValue) javaValue; return (LuaValue) javaValue;
} }
@@ -165,7 +175,7 @@ public class CoerceJavaToLua {
* {@code byte[]} will become {@link LuaString}; types inheriting from * {@code byte[]} will become {@link LuaString}; types inheriting from
* {@link LuaValue} will be returned without coercion; other types will * {@link LuaValue} will be returned without coercion; other types will
* become {@link LuaUserdata}. * become {@link LuaUserdata}.
* *
* @param o Java object needing conversion * @param o Java object needing conversion
* @return {@link LuaValue} corresponding to the supplied Java value. * @return {@link LuaValue} corresponding to the supplied Java value.
* @see LuaValue * @see LuaValue

View File

@@ -10,7 +10,7 @@
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -53,7 +53,7 @@ import org.luaj.vm2.LuaValue;
* <p> * <p>
* For data in lua tables, the various methods on {@link LuaTable} can be used * For data in lua tables, the various methods on {@link LuaTable} can be used
* directly to convert data to something more useful. * directly to convert data to something more useful.
* *
* @see org.luaj.vm2.lib.jse.LuajavaLib * @see org.luaj.vm2.lib.jse.LuajavaLib
* @see CoerceJavaToLua * @see CoerceJavaToLua
*/ */
@@ -63,15 +63,15 @@ public class CoerceLuaToJava {
static int SCORE_WRONG_TYPE = 0x100; static int SCORE_WRONG_TYPE = 0x100;
static int SCORE_UNCOERCIBLE = 0x10000; static int SCORE_UNCOERCIBLE = 0x10000;
static interface Coercion { interface Coercion {
public int score(LuaValue value); int score(LuaValue value);
public Object coerce(LuaValue value); Object coerce(LuaValue value);
}; }
/** /**
* Coerce a LuaValue value to a specified java class * Coerce a LuaValue value to a specified java class
* *
* @param value LuaValue to coerce * @param value LuaValue to coerce
* @param clazz Class to coerce into * @param clazz Class to coerce into
* @return Object of type clazz (or a subclass) with the corresponding * @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 Map COERCIONS = Collections.synchronizedMap(new HashMap());
static final class BoolCoercion implements Coercion { static final class BoolCoercion implements Coercion {
@Override
public String toString() { public String toString() {
return "BoolCoercion()"; return "BoolCoercion()";
} }
@Override
public int score(LuaValue value) { public int score(LuaValue value) {
switch (value.type()) { switch (value.type()) {
case LuaValue.TBOOLEAN: case LuaValue.TBOOLEAN:
@@ -96,6 +98,7 @@ public class CoerceLuaToJava {
return 1; return 1;
} }
@Override
public Object coerce(LuaValue value) { public Object coerce(LuaValue value) {
return value.toboolean()? Boolean.TRUE: Boolean.FALSE; 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" }; static final String[] TYPE_NAMES = { "byte", "char", "short", "int", "long", "float", "double" };
final int targetType; final int targetType;
@Override
public String toString() { public String toString() {
return "NumericCoercion(" + TYPE_NAMES[targetType] + ")"; return "NumericCoercion(" + TYPE_NAMES[targetType] + ")";
} }
@@ -120,6 +124,7 @@ public class CoerceLuaToJava {
this.targetType = targetType; this.targetType = targetType;
} }
@Override
public int score(LuaValue value) { public int score(LuaValue value) {
int fromStringPenalty = 0; int fromStringPenalty = 0;
if (value.type() == LuaValue.TSTRING) { if (value.type() == LuaValue.TSTRING) {
@@ -133,19 +138,19 @@ public class CoerceLuaToJava {
switch (targetType) { switch (targetType) {
case TARGET_TYPE_BYTE: { case TARGET_TYPE_BYTE: {
int i = value.toint(); 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: { case TARGET_TYPE_CHAR: {
int i = value.toint(); 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: { case TARGET_TYPE_SHORT: {
int i = value.toint(); 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: { case TARGET_TYPE_INT: {
int i = value.toint(); 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: case TARGET_TYPE_FLOAT:
return fromStringPenalty+1; return fromStringPenalty+1;
@@ -168,15 +173,15 @@ public class CoerceLuaToJava {
return SCORE_WRONG_TYPE; return SCORE_WRONG_TYPE;
case TARGET_TYPE_LONG: { case TARGET_TYPE_LONG: {
double d = value.todouble(); 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: { case TARGET_TYPE_FLOAT: {
double d = value.todouble(); 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: { case TARGET_TYPE_DOUBLE: {
double d = value.todouble(); 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: default:
return SCORE_WRONG_TYPE; return SCORE_WRONG_TYPE;
@@ -186,22 +191,23 @@ public class CoerceLuaToJava {
} }
} }
@Override
public Object coerce(LuaValue value) { public Object coerce(LuaValue value) {
switch (targetType) { switch (targetType) {
case TARGET_TYPE_BYTE: case TARGET_TYPE_BYTE:
return new Byte((byte) value.toint()); return Byte.valueOf((byte) value.toint());
case TARGET_TYPE_CHAR: case TARGET_TYPE_CHAR:
return new Character((char) value.toint()); return Character.valueOf((char) value.toint());
case TARGET_TYPE_SHORT: case TARGET_TYPE_SHORT:
return new Short((short) value.toint()); return Short.valueOf((short) value.toint());
case TARGET_TYPE_INT: case TARGET_TYPE_INT:
return new Integer((int) value.toint()); return Integer.valueOf(value.toint());
case TARGET_TYPE_LONG: case TARGET_TYPE_LONG:
return new Long((long) value.todouble()); return Long.valueOf((long) value.todouble());
case TARGET_TYPE_FLOAT: case TARGET_TYPE_FLOAT:
return new Float((float) value.todouble()); return Float.valueOf((float) value.todouble());
case TARGET_TYPE_DOUBLE: case TARGET_TYPE_DOUBLE:
return new Double((double) value.todouble()); return Double.valueOf(value.todouble());
default: default:
return null; return null;
} }
@@ -217,15 +223,17 @@ public class CoerceLuaToJava {
this.targetType = targetType; this.targetType = targetType;
} }
@Override
public String toString() { public String toString() {
return "StringCoercion(" + (targetType == TARGET_TYPE_STRING? "String": "byte[]") + ")"; return "StringCoercion(" + (targetType == TARGET_TYPE_STRING? "String": "byte[]") + ")";
} }
@Override
public int score(LuaValue value) { public int score(LuaValue value) {
switch (value.type()) { switch (value.type()) {
case LuaValue.TSTRING: case LuaValue.TSTRING:
return value.checkstring().isValidUtf8()? (targetType == TARGET_TYPE_STRING? 0: 1) return value.checkstring().isValidUtf8()? targetType == TARGET_TYPE_STRING? 0: 1
: (targetType == TARGET_TYPE_BYTES? 0: SCORE_WRONG_TYPE); : targetType == TARGET_TYPE_BYTES? 0: SCORE_WRONG_TYPE;
case LuaValue.TNIL: case LuaValue.TNIL:
return SCORE_NULL_VALUE; return SCORE_NULL_VALUE;
default: default:
@@ -233,6 +241,7 @@ public class CoerceLuaToJava {
} }
} }
@Override
public Object coerce(LuaValue value) { public Object coerce(LuaValue value) {
if (value.isnil()) if (value.isnil())
return null; return null;
@@ -254,10 +263,12 @@ public class CoerceLuaToJava {
this.componentCoercion = getCoercion(componentType); this.componentCoercion = getCoercion(componentType);
} }
@Override
public String toString() { public String toString() {
return "ArrayCoercion(" + componentType.getName() + ")"; return "ArrayCoercion(" + componentType.getName() + ")";
} }
@Override
public int score(LuaValue value) { public int score(LuaValue value) {
switch (value.type()) { switch (value.type()) {
case LuaValue.TTABLE: case LuaValue.TTABLE:
@@ -271,6 +282,7 @@ public class CoerceLuaToJava {
} }
} }
@Override
public Object coerce(LuaValue value) { public Object coerce(LuaValue value) {
switch (value.type()) { switch (value.type()) {
case LuaValue.TTABLE: { case LuaValue.TTABLE: {
@@ -293,7 +305,7 @@ public class CoerceLuaToJava {
/** /**
* Determine levels of inheritance between a base class and a subclass * Determine levels of inheritance between a base class and a subclass
* *
* @param baseclass base class to look for * @param baseclass base class to look for
* @param subclass class from which to start looking * @param subclass class from which to start looking
* @return number of inheritance levels between subclass and baseclass, or * @return number of inheritance levels between subclass and baseclass, or
@@ -306,8 +318,8 @@ public class CoerceLuaToJava {
return 0; return 0;
int min = Math.min(SCORE_UNCOERCIBLE, inheritanceLevels(baseclass, subclass.getSuperclass())+1); int min = Math.min(SCORE_UNCOERCIBLE, inheritanceLevels(baseclass, subclass.getSuperclass())+1);
Class[] ifaces = subclass.getInterfaces(); Class[] ifaces = subclass.getInterfaces();
for (int i = 0; i < ifaces.length; i++) for (Class element : ifaces)
min = Math.min(min, inheritanceLevels(baseclass, ifaces[i])+1); min = Math.min(min, inheritanceLevels(baseclass, element)+1);
return min; return min;
} }
@@ -318,10 +330,12 @@ public class CoerceLuaToJava {
this.targetType = targetType; this.targetType = targetType;
} }
@Override
public String toString() { public String toString() {
return "ObjectCoercion(" + targetType.getName() + ")"; return "ObjectCoercion(" + targetType.getName() + ")";
} }
@Override
public int score(LuaValue value) { public int score(LuaValue value) {
switch (value.type()) { switch (value.type()) {
case LuaValue.TNUMBER: case LuaValue.TNUMBER:
@@ -339,10 +353,12 @@ public class CoerceLuaToJava {
} }
} }
@Override
public Object coerce(LuaValue value) { public Object coerce(LuaValue value) {
switch (value.type()) { switch (value.type()) {
case LuaValue.TNUMBER: 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: case LuaValue.TBOOLEAN:
return value.toboolean()? Boolean.TRUE: Boolean.FALSE; return value.toboolean()? Boolean.TRUE: Boolean.FALSE;
case LuaValue.TSTRING: case LuaValue.TSTRING:

View File

@@ -10,7 +10,7 @@
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -35,13 +35,14 @@ import org.luaj.vm2.lib.OneArgFunction;
* <p> * <p>
* This class is not used directly. It is returned by calls to * This class is not used directly. It is returned by calls to
* {@link CoerceJavaToLua#coerce(Object)} when an array is supplied. * {@link CoerceJavaToLua#coerce(Object)} when an array is supplied.
* *
* @see CoerceJavaToLua * @see CoerceJavaToLua
* @see CoerceLuaToJava * @see CoerceLuaToJava
*/ */
class JavaArray extends LuaUserdata { class JavaArray extends LuaUserdata {
private static final class LenFunction extends OneArgFunction { private static final class LenFunction extends OneArgFunction {
@Override
public LuaValue call(LuaValue u) { public LuaValue call(LuaValue u) {
return LuaValue.valueOf(Array.getLength(((LuaUserdata) u).m_instance)); return LuaValue.valueOf(Array.getLength(((LuaUserdata) u).m_instance));
} }
@@ -60,6 +61,7 @@ class JavaArray extends LuaUserdata {
setmetatable(array_metatable); setmetatable(array_metatable);
} }
@Override
public LuaValue get(LuaValue key) { public LuaValue get(LuaValue key) {
if (key.equals(LENGTH)) if (key.equals(LENGTH))
return valueOf(Array.getLength(m_instance)); return valueOf(Array.getLength(m_instance));
@@ -72,6 +74,7 @@ class JavaArray extends LuaUserdata {
return super.get(key); return super.get(key);
} }
@Override
public void set(LuaValue key, LuaValue value) { public void set(LuaValue key, LuaValue value) {
if (key.isint()) { if (key.isint()) {
int i = key.toint()-1; int i = key.toint()-1;

View File

@@ -10,7 +10,7 @@
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -42,7 +42,7 @@ import org.luaj.vm2.LuaValue;
* <p> * <p>
* This class is not used directly. It is returned by calls to * This class is not used directly. It is returned by calls to
* {@link CoerceJavaToLua#coerce(Object)} when a Class is supplied. * {@link CoerceJavaToLua#coerce(Object)} when a Class is supplied.
* *
* @see CoerceJavaToLua * @see CoerceJavaToLua
* @see CoerceLuaToJava * @see CoerceLuaToJava
*/ */
@@ -68,6 +68,7 @@ class JavaClass extends JavaInstance implements CoerceJavaToLua.Coercion {
this.jclass = this; this.jclass = this;
} }
@Override
public LuaValue coerce(Object javaValue) { public LuaValue coerce(Object javaValue) {
return this; return this;
} }
@@ -76,8 +77,7 @@ class JavaClass extends JavaInstance implements CoerceJavaToLua.Coercion {
if (fields == null) { if (fields == null) {
Map m = new HashMap(); Map m = new HashMap();
Field[] f = ((Class) m_instance).getFields(); Field[] f = ((Class) m_instance).getFields();
for (int i = 0; i < f.length; i++) { for (Field fi : f) {
Field fi = f[i];
if (Modifier.isPublic(fi.getModifiers())) { if (Modifier.isPublic(fi.getModifiers())) {
m.put(LuaValue.valueOf(fi.getName()), fi); m.put(LuaValue.valueOf(fi.getName()), fi);
try { try {
@@ -96,8 +96,7 @@ class JavaClass extends JavaInstance implements CoerceJavaToLua.Coercion {
if (methods == null) { if (methods == null) {
Map namedlists = new HashMap(); Map namedlists = new HashMap();
Method[] m = ((Class) m_instance).getMethods(); Method[] m = ((Class) m_instance).getMethods();
for (int i = 0; i < m.length; i++) { for (Method mi : m) {
Method mi = m[i];
if (Modifier.isPublic(mi.getModifiers())) { if (Modifier.isPublic(mi.getModifiers())) {
String name = mi.getName(); String name = mi.getName();
List list = (List) namedlists.get(name); List list = (List) namedlists.get(name);
@@ -109,9 +108,9 @@ class JavaClass extends JavaInstance implements CoerceJavaToLua.Coercion {
Map map = new HashMap(); Map map = new HashMap();
Constructor[] c = ((Class) m_instance).getConstructors(); Constructor[] c = ((Class) m_instance).getConstructors();
List list = new ArrayList(); List list = new ArrayList();
for (int i = 0; i < c.length; i++) for (Constructor element : c)
if (Modifier.isPublic(c[i].getModifiers())) if (Modifier.isPublic(element.getModifiers()))
list.add(JavaConstructor.forConstructor(c[i])); list.add(JavaConstructor.forConstructor(element));
switch (list.size()) { switch (list.size()) {
case 0: case 0:
break; break;
@@ -140,8 +139,7 @@ class JavaClass extends JavaInstance implements CoerceJavaToLua.Coercion {
if (innerclasses == null) { if (innerclasses == null) {
Map m = new HashMap(); Map m = new HashMap();
Class[] c = ((Class) m_instance).getClasses(); Class[] c = ((Class) m_instance).getClasses();
for (int i = 0; i < c.length; i++) { for (Class ci : c) {
Class ci = c[i];
String name = ci.getName(); String name = ci.getName();
String stub = name.substring(Math.max(name.lastIndexOf('$'), name.lastIndexOf('.'))+1); String stub = name.substring(Math.max(name.lastIndexOf('$'), name.lastIndexOf('.'))+1);
m.put(LuaValue.valueOf(stub), ci); m.put(LuaValue.valueOf(stub), ci);

View File

@@ -10,7 +10,7 @@
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -40,7 +40,7 @@ import org.luaj.vm2.lib.VarArgFunction;
* <p> * <p>
* This class is not used directly. It is returned by calls to * This class is not used directly. It is returned by calls to
* {@link JavaClass#new(LuaValue key)} when the value of key is "new". * {@link JavaClass#new(LuaValue key)} when the value of key is "new".
* *
* @see CoerceJavaToLua * @see CoerceJavaToLua
* @see CoerceLuaToJava * @see CoerceLuaToJava
*/ */
@@ -66,6 +66,7 @@ class JavaConstructor extends JavaMember {
this.constructor = c; this.constructor = c;
} }
@Override
public Varargs invoke(Varargs args) { public Varargs invoke(Varargs args) {
Object[] a = convertArgs(args); Object[] a = convertArgs(args);
try { try {
@@ -93,20 +94,21 @@ class JavaConstructor extends JavaMember {
this.constructors = c; this.constructors = c;
} }
@Override
public Varargs invoke(Varargs args) { public Varargs invoke(Varargs args) {
JavaConstructor best = null; JavaConstructor best = null;
int score = CoerceLuaToJava.SCORE_UNCOERCIBLE; int score = CoerceLuaToJava.SCORE_UNCOERCIBLE;
for (int i = 0; i < constructors.length; i++) { for (JavaConstructor constructor : constructors) {
int s = constructors[i].score(args); int s = constructor.score(args);
if (s < score) { if (s < score) {
score = s; score = s;
best = constructors[i]; best = constructor;
if (score == 0) if (score == 0)
break; break;
} }
} }
// any match? // any match?
if (best == null) if (best == null)
LuaValue.error("no coercible public method"); LuaValue.error("no coercible public method");

View File

@@ -10,7 +10,7 @@
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -34,7 +34,7 @@ import org.luaj.vm2.LuaValue;
* <p> * <p>
* This class is not used directly. It is returned by calls to * This class is not used directly. It is returned by calls to
* {@link CoerceJavaToLua#coerce(Object)} when a subclass of Object is supplied. * {@link CoerceJavaToLua#coerce(Object)} when a subclass of Object is supplied.
* *
* @see CoerceJavaToLua * @see CoerceJavaToLua
* @see CoerceLuaToJava * @see CoerceLuaToJava
*/ */
@@ -46,6 +46,7 @@ class JavaInstance extends LuaUserdata {
super(instance); super(instance);
} }
@Override
public LuaValue get(LuaValue key) { public LuaValue get(LuaValue key) {
if (jclass == null) if (jclass == null)
jclass = JavaClass.forClass(m_instance.getClass()); jclass = JavaClass.forClass(m_instance.getClass());
@@ -65,6 +66,7 @@ class JavaInstance extends LuaUserdata {
return super.get(key); return super.get(key);
} }
@Override
public void set(LuaValue key, LuaValue value) { public void set(LuaValue key, LuaValue value) {
if (jclass == null) if (jclass == null)
jclass = JavaClass.forClass(m_instance.getClass()); jclass = JavaClass.forClass(m_instance.getClass());

View File

@@ -10,7 +10,7 @@
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * 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> * <p>
* This class is not used directly. It is an abstract base class for * This class is not used directly. It is an abstract base class for
* {@link JavaConstructor} and {@link JavaMethod}. * {@link JavaConstructor} and {@link JavaMethod}.
* *
* @see JavaConstructor * @see JavaConstructor
* @see JavaMethod * @see JavaMethod
* @see CoerceJavaToLua * @see CoerceJavaToLua
@@ -47,7 +47,7 @@ abstract class JavaMember extends VarArgFunction {
final Coercion varargs; final Coercion varargs;
protected JavaMember(Class[] params, int modifiers) { 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]; fixedargs = new CoerceLuaToJava.Coercion[isvarargs? params.length-1: params.length];
for (int i = 0; i < fixedargs.length; i++) for (int i = 0; i < fixedargs.length; i++)
fixedargs[i] = CoerceLuaToJava.getCoercion(params[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 * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -39,7 +39,7 @@ import org.luaj.vm2.Varargs;
* <p> * <p>
* This class is not used directly. It is returned by calls to calls to * This class is not used directly. It is returned by calls to calls to
* {@link JavaInstance#get(LuaValue key)} when a method is named. * {@link JavaInstance#get(LuaValue key)} when a method is named.
* *
* @see CoerceJavaToLua * @see CoerceJavaToLua
* @see CoerceLuaToJava * @see CoerceLuaToJava
*/ */
@@ -70,22 +70,27 @@ class JavaMethod extends JavaMember {
} }
} }
@Override
public LuaValue call() { public LuaValue call() {
return error("method cannot be called without instance"); return error("method cannot be called without instance");
} }
@Override
public LuaValue call(LuaValue arg) { public LuaValue call(LuaValue arg) {
return invokeMethod(arg.checkuserdata(), LuaValue.NONE); return invokeMethod(arg.checkuserdata(), LuaValue.NONE);
} }
@Override
public LuaValue call(LuaValue arg1, LuaValue arg2) { public LuaValue call(LuaValue arg1, LuaValue arg2) {
return invokeMethod(arg1.checkuserdata(), arg2); return invokeMethod(arg1.checkuserdata(), arg2);
} }
@Override
public LuaValue call(LuaValue arg1, LuaValue arg2, LuaValue arg3) { public LuaValue call(LuaValue arg1, LuaValue arg2, LuaValue arg3) {
return invokeMethod(arg1.checkuserdata(), LuaValue.varargsOf(arg2, arg3)); return invokeMethod(arg1.checkuserdata(), LuaValue.varargsOf(arg2, arg3));
} }
@Override
public Varargs invoke(Varargs args) { public Varargs invoke(Varargs args) {
return invokeMethod(args.checkuserdata(1), args.subargs(2)); return invokeMethod(args.checkuserdata(1), args.subargs(2));
} }
@@ -118,22 +123,27 @@ class JavaMethod extends JavaMember {
this.methods = methods; this.methods = methods;
} }
@Override
public LuaValue call() { public LuaValue call() {
return error("method cannot be called without instance"); return error("method cannot be called without instance");
} }
@Override
public LuaValue call(LuaValue arg) { public LuaValue call(LuaValue arg) {
return invokeBestMethod(arg.checkuserdata(), LuaValue.NONE); return invokeBestMethod(arg.checkuserdata(), LuaValue.NONE);
} }
@Override
public LuaValue call(LuaValue arg1, LuaValue arg2) { public LuaValue call(LuaValue arg1, LuaValue arg2) {
return invokeBestMethod(arg1.checkuserdata(), arg2); return invokeBestMethod(arg1.checkuserdata(), arg2);
} }
@Override
public LuaValue call(LuaValue arg1, LuaValue arg2, LuaValue arg3) { public LuaValue call(LuaValue arg1, LuaValue arg2, LuaValue arg3) {
return invokeBestMethod(arg1.checkuserdata(), LuaValue.varargsOf(arg2, arg3)); return invokeBestMethod(arg1.checkuserdata(), LuaValue.varargsOf(arg2, arg3));
} }
@Override
public Varargs invoke(Varargs args) { public Varargs invoke(Varargs args) {
return invokeBestMethod(args.checkuserdata(1), args.subargs(2)); return invokeBestMethod(args.checkuserdata(1), args.subargs(2));
} }
@@ -141,17 +151,17 @@ class JavaMethod extends JavaMember {
private LuaValue invokeBestMethod(Object instance, Varargs args) { private LuaValue invokeBestMethod(Object instance, Varargs args) {
JavaMethod best = null; JavaMethod best = null;
int score = CoerceLuaToJava.SCORE_UNCOERCIBLE; int score = CoerceLuaToJava.SCORE_UNCOERCIBLE;
for (int i = 0; i < methods.length; i++) { for (JavaMethod method : methods) {
int s = methods[i].score(args); int s = method.score(args);
if (s < score) { if (s < score) {
score = s; score = s;
best = methods[i]; best = method;
if (score == 0) if (score == 0)
break; break;
} }
} }
// any match? // any match?
if (best == null) if (best == null)
LuaValue.error("no coercible public method"); LuaValue.error("no coercible public method");

View File

@@ -10,7 +10,7 @@
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -47,7 +47,7 @@ import org.luaj.vm2.lib.ResourceFinder;
* <p> * <p>
* Typically, this library is included as part of a call to * Typically, this library is included as part of a call to
* {@link org.luaj.vm2.lib.jse.JsePlatform#standardGlobals()} * {@link org.luaj.vm2.lib.jse.JsePlatform#standardGlobals()}
* *
* <pre> * <pre>
* { * {
* &#64;code * &#64;code
@@ -59,7 +59,7 @@ import org.luaj.vm2.lib.ResourceFinder;
* For special cases where the smallest possible footprint is desired, a minimal * For special cases where the smallest possible footprint is desired, a minimal
* set of libraries could be loaded directly via {@link Globals#load(LuaValue)} * set of libraries could be loaded directly via {@link Globals#load(LuaValue)}
* using code such as: * using code such as:
* *
* <pre> * <pre>
* { * {
* &#64;code * &#64;code
@@ -73,7 +73,7 @@ import org.luaj.vm2.lib.ResourceFinder;
* case. * case.
* <p> * <p>
* This is a direct port of the corresponding library in C. * This is a direct port of the corresponding library in C.
* *
* @see Globals * @see Globals
* @see BaseLib * @see BaseLib
* @see ResourceFinder * @see ResourceFinder
@@ -95,11 +95,12 @@ public class JseBaseLib extends org.luaj.vm2.lib.BaseLib {
* <P> * <P>
* Specifically, extend the library loading to set the default value for * Specifically, extend the library loading to set the default value for
* {@link Globals#STDIN} * {@link Globals#STDIN}
* *
* @param modname the module name supplied if this is loaded via 'require'. * @param modname the module name supplied if this is loaded via 'require'.
* @param env the environment to load into, which must be a Globals * @param env the environment to load into, which must be a Globals
* instance. * instance.
*/ */
@Override
public LuaValue call(LuaValue modname, LuaValue env) { public LuaValue call(LuaValue modname, LuaValue env) {
super.call(modname, env); super.call(modname, env);
env.checkglobals().STDIN = System.in; 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 * Try to open a file in the current working directory, or fall back to base
* opener if not found. * opener if not found.
* *
* This implementation attempts to open the file using new File(filename). * 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 * 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. * in the class path if not found as a plain file.
* *
* @see org.luaj.vm2.lib.BaseLib * @see org.luaj.vm2.lib.BaseLib
* @see org.luaj.vm2.lib.ResourceFinder * @see org.luaj.vm2.lib.ResourceFinder
* *
* @param filename * @param filename
* @return InputStream, or null if not found. * @return InputStream, or null if not found.
*/ */
@Override
public InputStream findResource(String filename) { public InputStream findResource(String filename) {
File f = new File(filename); File f = new File(filename);
if (!f.exists()) if (!f.exists())

View File

@@ -10,7 +10,7 @@
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -44,7 +44,7 @@ import org.luaj.vm2.lib.LibFunction;
* <p> * <p>
* Typically, this library is included as part of a call to * Typically, this library is included as part of a call to
* {@link org.luaj.vm2.lib.jse.JsePlatform#standardGlobals()} * {@link org.luaj.vm2.lib.jse.JsePlatform#standardGlobals()}
* *
* <pre> * <pre>
* { * {
* &#64;code * &#64;code
@@ -56,7 +56,7 @@ import org.luaj.vm2.lib.LibFunction;
* For special cases where the smallest possible footprint is desired, a minimal * For special cases where the smallest possible footprint is desired, a minimal
* set of libraries could be loaded directly via {@link Globals#load(LuaValue)} * set of libraries could be loaded directly via {@link Globals#load(LuaValue)}
* using code such as: * using code such as:
* *
* <pre> * <pre>
* { * {
* &#64;code * &#64;code
@@ -73,7 +73,7 @@ import org.luaj.vm2.lib.LibFunction;
* <p> * <p>
* This has been implemented to match as closely as possible the behavior in the * This has been implemented to match as closely as possible the behavior in the
* corresponding library in C. * corresponding library in C.
* *
* @see LibFunction * @see LibFunction
* @see org.luaj.vm2.lib.jse.JsePlatform * @see org.luaj.vm2.lib.jse.JsePlatform
* @see org.luaj.vm2.lib.jme.JmePlatform * @see org.luaj.vm2.lib.jme.JmePlatform
@@ -84,18 +84,22 @@ import org.luaj.vm2.lib.LibFunction;
*/ */
public class JseIoLib extends IoLib { public class JseIoLib extends IoLib {
@Override
protected File wrapStdin() throws IOException { protected File wrapStdin() throws IOException {
return new StdinFile(); return new StdinFile();
} }
@Override
protected File wrapStdout() throws IOException { protected File wrapStdout() throws IOException {
return new StdoutFile(FTYPE_STDOUT); return new StdoutFile(FTYPE_STDOUT);
} }
@Override
protected File wrapStderr() throws IOException { protected File wrapStderr() throws IOException {
return new StdoutFile(FTYPE_STDERR); return new StdoutFile(FTYPE_STDERR);
} }
@Override
protected File openFile(String filename, boolean readMode, boolean appendMode, boolean updateMode, protected File openFile(String filename, boolean readMode, boolean appendMode, boolean updateMode,
boolean binaryMode) throws IOException { boolean binaryMode) throws IOException {
RandomAccessFile f = new RandomAccessFile(filename, readMode? "r": "rw"); RandomAccessFile f = new RandomAccessFile(filename, readMode? "r": "rw");
@@ -108,11 +112,13 @@ public class JseIoLib extends IoLib {
return new FileImpl(f); return new FileImpl(f);
} }
@Override
protected File openProgram(String prog, String mode) throws IOException { protected File openProgram(String prog, String mode) throws IOException {
final Process p = Runtime.getRuntime().exec(prog); final Process p = Runtime.getRuntime().exec(prog);
return "w".equals(mode)? new FileImpl(p.getOutputStream()): new FileImpl(p.getInputStream()); return "w".equals(mode)? new FileImpl(p.getOutputStream()): new FileImpl(p.getInputStream());
} }
@Override
protected File tmpFile() throws IOException { protected File tmpFile() throws IOException {
java.io.File f = java.io.File.createTempFile(".luaj", "bin"); java.io.File f = java.io.File.createTempFile(".luaj", "bin");
f.deleteOnExit(); f.deleteOnExit();
@@ -148,14 +154,17 @@ public class JseIoLib extends IoLib {
this(null, null, o); this(null, null, o);
} }
@Override
public String tojstring() { public String tojstring() {
return "file (" + (this.closed? "closed": String.valueOf(this.hashCode())) + ")"; return "file (" + (this.closed? "closed": String.valueOf(this.hashCode())) + ")";
} }
@Override
public boolean isstdfile() { public boolean isstdfile() {
return file == null; return file == null;
} }
@Override
public void close() throws IOException { public void close() throws IOException {
closed = true; closed = true;
if (file != null) { if (file != null) {
@@ -163,11 +172,13 @@ public class JseIoLib extends IoLib {
} }
} }
@Override
public void flush() throws IOException { public void flush() throws IOException {
if (os != null) if (os != null)
os.flush(); os.flush();
} }
@Override
public void write(LuaString s) throws IOException { public void write(LuaString s) throws IOException {
if (os != null) if (os != null)
os.write(s.m_bytes, s.m_offset, s.m_length); os.write(s.m_bytes, s.m_offset, s.m_length);
@@ -179,10 +190,12 @@ public class JseIoLib extends IoLib {
flush(); flush();
} }
@Override
public boolean isclosed() { public boolean isclosed() {
return closed; return closed;
} }
@Override
public int seek(String option, int pos) throws IOException { public int seek(String option, int pos) throws IOException {
if (file != null) { if (file != null) {
if ("set".equals(option)) { if ("set".equals(option)) {
@@ -198,16 +211,19 @@ public class JseIoLib extends IoLib {
return 0; return 0;
} }
@Override
public void setvbuf(String mode, int size) { public void setvbuf(String mode, int size) {
nobuffer = "no".equals(mode); nobuffer = "no".equals(mode);
} }
// get length remaining to read // get length remaining to read
@Override
public int remaining() throws IOException { public int remaining() throws IOException {
return file != null? (int) (file.length()-file.getFilePointer()): -1; return file != null? (int) (file.length()-file.getFilePointer()): -1;
} }
// peek ahead one character // peek ahead one character
@Override
public int peek() throws IOException { public int peek() throws IOException {
if (is != null) { if (is != null) {
is.mark(1); is.mark(1);
@@ -225,6 +241,7 @@ public class JseIoLib extends IoLib {
} }
// 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 { public int read() throws IOException {
if (is != null) if (is != null)
return is.read(); return is.read();
@@ -236,6 +253,7 @@ public class JseIoLib extends IoLib {
} }
// return number of bytes read if positive, -1 if eof, throws IOException // return number of bytes read if positive, -1 if eof, throws IOException
@Override
public int read(byte[] bytes, int offset, int length) throws IOException { public int read(byte[] bytes, int offset, int length) throws IOException {
if (file != null) { if (file != null) {
return file.read(bytes, offset, length); return file.read(bytes, offset, length);
@@ -255,51 +273,63 @@ public class JseIoLib extends IoLib {
this.file_type = file_type; this.file_type = file_type;
} }
@Override
public String tojstring() { public String tojstring() {
return "file (" + this.hashCode() + ")"; 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 { public void write(LuaString string) throws IOException {
getPrintStream().write(string.m_bytes, string.m_offset, string.m_length); getPrintStream().write(string.m_bytes, string.m_offset, string.m_length);
} }
@Override
public void flush() throws IOException { public void flush() throws IOException {
getPrintStream().flush(); getPrintStream().flush();
} }
@Override
public boolean isstdfile() { public boolean isstdfile() {
return true; return true;
} }
@Override
public void close() throws IOException { public void close() throws IOException {
// do not close std files. // do not close std files.
} }
@Override
public boolean isclosed() { public boolean isclosed() {
return false; return false;
} }
@Override
public int seek(String option, int bytecount) throws IOException { public int seek(String option, int bytecount) throws IOException {
return 0; return 0;
} }
@Override
public void setvbuf(String mode, int size) { public void setvbuf(String mode, int size) {
} }
@Override
public int remaining() throws IOException { public int remaining() throws IOException {
return 0; return 0;
} }
@Override
public int peek() throws IOException, EOFException { public int peek() throws IOException, EOFException {
return 0; return 0;
} }
@Override
public int read() throws IOException, EOFException { public int read() throws IOException, EOFException {
return 0; return 0;
} }
@Override
public int read(byte[] bytes, int offset, int length) throws IOException { public int read(byte[] bytes, int offset, int length) throws IOException {
return 0; return 0;
} }
@@ -309,39 +339,49 @@ public class JseIoLib extends IoLib {
private StdinFile() { private StdinFile() {
} }
@Override
public String tojstring() { public String tojstring() {
return "file (" + this.hashCode() + ")"; return "file (" + this.hashCode() + ")";
} }
@Override
public void write(LuaString string) throws IOException { public void write(LuaString string) throws IOException {
} }
@Override
public void flush() throws IOException { public void flush() throws IOException {
} }
@Override
public boolean isstdfile() { public boolean isstdfile() {
return true; return true;
} }
@Override
public void close() throws IOException { public void close() throws IOException {
// do not close std files. // do not close std files.
} }
@Override
public boolean isclosed() { public boolean isclosed() {
return false; return false;
} }
@Override
public int seek(String option, int bytecount) throws IOException { public int seek(String option, int bytecount) throws IOException {
return 0; return 0;
} }
@Override
public void setvbuf(String mode, int size) { public void setvbuf(String mode, int size) {
} }
@Override
public int remaining() throws IOException { public int remaining() throws IOException {
return -1; return -1;
} }
@Override
public int peek() throws IOException, EOFException { public int peek() throws IOException, EOFException {
globals.STDIN.mark(1); globals.STDIN.mark(1);
int c = globals.STDIN.read(); int c = globals.STDIN.read();
@@ -349,10 +389,12 @@ public class JseIoLib extends IoLib {
return c; return c;
} }
@Override
public int read() throws IOException, EOFException { public int read() throws IOException, EOFException {
return globals.STDIN.read(); return globals.STDIN.read();
} }
@Override
public int read(byte[] bytes, int offset, int length) throws IOException { public int read(byte[] bytes, int offset, int length) throws IOException {
return globals.STDIN.read(bytes, offset, length); 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 * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -35,7 +35,7 @@ import org.luaj.vm2.lib.TwoArgFunction;
* <p> * <p>
* Typically, this library is included as part of a call to * Typically, this library is included as part of a call to
* {@link org.luaj.vm2.lib.jse.JsePlatform#standardGlobals()} * {@link org.luaj.vm2.lib.jse.JsePlatform#standardGlobals()}
* *
* <pre> * <pre>
* { * {
* &#64;code * &#64;code
@@ -47,7 +47,7 @@ import org.luaj.vm2.lib.TwoArgFunction;
* For special cases where the smallest possible footprint is desired, a minimal * For special cases where the smallest possible footprint is desired, a minimal
* set of libraries could be loaded directly via {@link Globals#load(LuaValue)} * set of libraries could be loaded directly via {@link Globals#load(LuaValue)}
* using code such as: * using code such as:
* *
* <pre> * <pre>
* { * {
* &#64;code * &#64;code
@@ -64,7 +64,7 @@ import org.luaj.vm2.lib.TwoArgFunction;
* <p> * <p>
* This has been implemented to match as closely as possible the behavior in the * This has been implemented to match as closely as possible the behavior in the
* corresponding library in C. * corresponding library in C.
* *
* @see LibFunction * @see LibFunction
* @see org.luaj.vm2.lib.jse.JsePlatform * @see org.luaj.vm2.lib.jse.JsePlatform
* @see org.luaj.vm2.lib.jme.JmePlatform * @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 * Specifically, adds all library functions that can be implemented directly
* in JSE but not JME: acos, asin, atan, atan2, cosh, exp, log, pow, sinh, * in JSE but not JME: acos, asin, atan, atan2, cosh, exp, log, pow, sinh,
* and tanh. * and tanh.
* *
* @param modname the module name supplied if this is loaded via 'require'. * @param modname the module name supplied if this is loaded via 'require'.
* @param env the environment to load into, which must be a Globals * @param env the environment to load into, which must be a Globals
* instance. * instance.
*/ */
@Override
public LuaValue call(LuaValue modname, LuaValue env) { public LuaValue call(LuaValue modname, LuaValue env) {
super.call(modname, env); super.call(modname, env);
LuaValue math = env.get("math"); LuaValue math = env.get("math");
@@ -108,28 +109,34 @@ public class JseMathLib extends org.luaj.vm2.lib.MathLib {
} }
static final class acos extends UnaryOp { static final class acos extends UnaryOp {
@Override
protected double call(double d) { return Math.acos(d); } protected double call(double d) { return Math.acos(d); }
} }
static final class asin extends UnaryOp { static final class asin extends UnaryOp {
@Override
protected double call(double d) { return Math.asin(d); } protected double call(double d) { return Math.asin(d); }
} }
static final class atan2 extends TwoArgFunction { static final class atan2 extends TwoArgFunction {
@Override
public LuaValue call(LuaValue x, LuaValue y) { public LuaValue call(LuaValue x, LuaValue y) {
return valueOf(Math.atan2(x.checkdouble(), y.optdouble(1))); return valueOf(Math.atan2(x.checkdouble(), y.optdouble(1)));
} }
} }
static final class cosh extends UnaryOp { static final class cosh extends UnaryOp {
@Override
protected double call(double d) { return Math.cosh(d); } protected double call(double d) { return Math.cosh(d); }
} }
static final class exp extends UnaryOp { static final class exp extends UnaryOp {
@Override
protected double call(double d) { return Math.exp(d); } protected double call(double d) { return Math.exp(d); }
} }
static final class log extends TwoArgFunction { static final class log extends TwoArgFunction {
@Override
public LuaValue call(LuaValue x, LuaValue base) { public LuaValue call(LuaValue x, LuaValue base) {
double nat = Math.log(x.checkdouble()); double nat = Math.log(x.checkdouble());
double b = base.optdouble(Math.E); 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 { static final class pow extends BinaryOp {
@Override
protected double call(double x, double y) { return Math.pow(x, y); } protected double call(double x, double y) { return Math.pow(x, y); }
} }
static final class sinh extends UnaryOp { static final class sinh extends UnaryOp {
@Override
protected double call(double d) { return Math.sinh(d); } protected double call(double d) { return Math.sinh(d); }
} }
static final class tanh extends UnaryOp { static final class tanh extends UnaryOp {
@Override
protected double call(double d) { return Math.tanh(d); } protected double call(double d) { return Math.tanh(d); }
} }
/** Faster, better version of pow() used by arithmetic operator ^ */ /** Faster, better version of pow() used by arithmetic operator ^ */
@Override
public double dpow_lib(double a, double b) { public double dpow_lib(double a, double b) {
return Math.pow(a, b); return Math.pow(a, b);
} }

View File

@@ -10,7 +10,7 @@
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -49,7 +49,7 @@ import org.luaj.vm2.lib.OsLib;
* <p> * <p>
* Typically, this library is included as part of a call to * Typically, this library is included as part of a call to
* {@link org.luaj.vm2.lib.jse.JsePlatform#standardGlobals()} * {@link org.luaj.vm2.lib.jse.JsePlatform#standardGlobals()}
* *
* <pre> * <pre>
* { * {
* &#64;code * &#64;code
@@ -61,7 +61,7 @@ import org.luaj.vm2.lib.OsLib;
* For special cases where the smallest possible footprint is desired, a minimal * For special cases where the smallest possible footprint is desired, a minimal
* set of libraries could be loaded directly via {@link Globals#load(LuaValue)} * set of libraries could be loaded directly via {@link Globals#load(LuaValue)}
* using code such as: * using code such as:
* *
* <pre> * <pre>
* { * {
* &#64;code * &#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 * However, other libraries such as <em>MathLib</em> are not loaded in this
* case. * case.
* <p> * <p>
* *
* @see LibFunction * @see LibFunction
* @see OsLib * @see OsLib
* @see org.luaj.vm2.lib.jse.JsePlatform * @see org.luaj.vm2.lib.jse.JsePlatform
@@ -99,11 +99,13 @@ public class JseOsLib extends org.luaj.vm2.lib.OsLib {
public JseOsLib() { public JseOsLib() {
} }
@Override
protected String getenv(String varname) { protected String getenv(String varname) {
String s = System.getenv(varname); String s = System.getenv(varname);
return s != null? s: System.getProperty(varname); return s != null? s: System.getProperty(varname);
} }
@Override
protected Varargs execute(String command) { protected Varargs execute(String command) {
int exitValue; int exitValue;
try { try {
@@ -120,6 +122,7 @@ public class JseOsLib extends org.luaj.vm2.lib.OsLib {
return varargsOf(NIL, valueOf("signal"), valueOf(exitValue)); return varargsOf(NIL, valueOf("signal"), valueOf(exitValue));
} }
@Override
protected void remove(String filename) throws IOException { protected void remove(String filename) throws IOException {
File f = new File(filename); File f = new File(filename);
if (!f.exists()) if (!f.exists())
@@ -128,6 +131,7 @@ public class JseOsLib extends org.luaj.vm2.lib.OsLib {
throw new IOException("Failed to delete"); throw new IOException("Failed to delete");
} }
@Override
protected void rename(String oldname, String newname) throws IOException { protected void rename(String oldname, String newname) throws IOException {
File f = new File(oldname); File f = new File(oldname);
if (!f.exists()) if (!f.exists())
@@ -136,6 +140,7 @@ public class JseOsLib extends org.luaj.vm2.lib.OsLib {
throw new IOException("Failed to rename"); throw new IOException("Failed to rename");
} }
@Override
protected String tmpname() { protected String tmpname() {
try { try {
java.io.File f = java.io.File.createTempFile(TMP_PREFIX, TMP_SUFFIX); 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 * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * 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()} * {@link #standardGlobals()} or debug globals using {@link #debugGlobals()}
* <p> * <p>
* A simple example of initializing globals and using them from Java is: * A simple example of initializing globals and using them from Java is:
* *
* <pre> * <pre>
* { * {
* &#64;code * &#64;code
@@ -52,7 +52,7 @@ import org.luaj.vm2.lib.TableLib;
* </pre> * </pre>
* <p> * <p>
* Once globals are created, a simple way to load and run a script is: * Once globals are created, a simple way to load and run a script is:
* *
* <pre> * <pre>
* {@code * {@code
* globals.load( new FileInputStream("main.lua"), "main.lua" ).call(); * globals.load( new FileInputStream("main.lua"), "main.lua" ).call();
@@ -60,13 +60,13 @@ import org.luaj.vm2.lib.TableLib;
* </pre> * </pre>
* <p> * <p>
* although {@code require} could also be used: * although {@code require} could also be used:
* *
* <pre> * <pre>
* {@code * {@code
* globals.get("require").call(LuaValue.valueOf("main")); * globals.get("require").call(LuaValue.valueOf("main"));
* } * }
* </pre> * </pre>
* *
* For this to succeed, the file "main.lua" must be in the current directory or * 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 * a resource. See {@link org.luaj.vm2.lib.jse.JseBaseLib} for details on
* finding scripts using {@link ResourceFinder}. * finding scripts using {@link ResourceFinder}.
@@ -93,7 +93,7 @@ import org.luaj.vm2.lib.TableLib;
* library {@link DebugLib}. * library {@link DebugLib}.
* <p> * <p>
* The class ensures that initialization is done in the correct order. * The class ensures that initialization is done in the correct order.
* *
* @see Globals * @see Globals
* @see org.luaj.vm2.lib.jme.JmePlatform * @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. * Create a standard set of globals for JSE including all the libraries.
* *
* @return Table of globals initialized with the standard JSE libraries * @return Table of globals initialized with the standard JSE libraries
* @see #debugGlobals() * @see #debugGlobals()
* @see org.luaj.vm2.lib.jse.JsePlatform * @see org.luaj.vm2.lib.jse.JsePlatform
@@ -126,7 +126,7 @@ public class JsePlatform {
/** /**
* Create standard globals including the {@link DebugLib} library. * Create standard globals including the {@link DebugLib} library.
* *
* @return Table of globals initialized with the standard JSE and debug * @return Table of globals initialized with the standard JSE and debug
* libraries * libraries
* @see #standardGlobals() * @see #standardGlobals()
@@ -144,7 +144,7 @@ public class JsePlatform {
* Simple wrapper for invoking a lua function with command line arguments. * Simple wrapper for invoking a lua function with command line arguments.
* The supplied function is first given a new Globals object as its * The supplied function is first given a new Globals object as its
* environment then the program is run with arguments. * environment then the program is run with arguments.
* *
* @return {@link Varargs} containing any values returned by mainChunk. * @return {@link Varargs} containing any values returned by mainChunk.
*/ */
public static Varargs luaMain(LuaValue mainChunk, String[] args) { 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 * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * 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 * Construct a process around a command, with specified streams to redirect
* input and output to. * input and output to.
* *
* @param cmd The command to execute, including arguments, if any * @param cmd The command to execute, including arguments, if any
* @param stdin Optional InputStream to read from as process input, or null * @param stdin Optional InputStream to read from as process input, or null
* if input is not needed. * if input is not needed.
@@ -54,7 +54,7 @@ public class JseProcess {
/** /**
* Construct a process around a command, with specified streams to redirect * Construct a process around a command, with specified streams to redirect
* input and output to. * input and output to.
* *
* @param cmd The command to execute, including arguments, if any * @param cmd The command to execute, including arguments, if any
* @param stdin Optional InputStream to read from as process input, or null * @param stdin Optional InputStream to read from as process input, or null
* if input is not needed. * if input is not needed.
@@ -83,7 +83,7 @@ public class JseProcess {
/** /**
* Wait for the process to complete, and all pending output to finish. * Wait for the process to complete, and all pending output to finish.
* *
* @return The exit status. * @return The exit status.
* @throws InterruptedException * @throws InterruptedException
*/ */
@@ -102,7 +102,7 @@ public class JseProcess {
/** Create a thread to copy bytes from input to output. */ /** Create a thread to copy bytes from input to output. */
private Thread copyBytes(final InputStream input, final OutputStream output, final InputStream ownedInput, private Thread copyBytes(final InputStream input, final OutputStream output, final InputStream ownedInput,
final OutputStream ownedOutput) { final OutputStream ownedOutput) {
Thread t = (new CopyThread(output, ownedOutput, ownedInput, input)); Thread t = new CopyThread(output, ownedOutput, ownedInput, input);
t.start(); t.start();
return t; return t;
} }
@@ -120,6 +120,7 @@ public class JseProcess {
this.input = input; this.input = input;
} }
@Override
public void run() { public void run() {
try { try {
byte[] buf = new byte[1024]; byte[] buf = new byte[1024];

View File

@@ -10,7 +10,7 @@
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * 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() { public JseStringLib() {
} }
@Override
protected String format(String src, double x) { protected String format(String src, double x) {
String out; String out;
try { try {
out = String.format(src, new Object[] { Double.valueOf(x) }); out = String.format(src, Double.valueOf(x));
} catch (Throwable e) { } catch (Throwable e) {
out = super.format(src, x); out = super.format(src, x);
} }

View File

@@ -10,7 +10,7 @@
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * 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 * bind java classes and methods to lua dynamically. The API is documented on
* the <a href="http://www.keplerproject.org/luajava/">luajava</a> documentation * the <a href="http://www.keplerproject.org/luajava/">luajava</a> documentation
* pages. * pages.
* *
* <p> * <p>
* Typically, this library is included as part of a call to * Typically, this library is included as part of a call to
* {@link org.luaj.vm2.lib.jse.JsePlatform#standardGlobals()} * {@link org.luaj.vm2.lib.jse.JsePlatform#standardGlobals()}
* *
* <pre> * <pre>
* { * {
* &#64;code * &#64;code
@@ -60,7 +60,7 @@ import org.luaj.vm2.lib.VarArgFunction;
* <p> * <p>
* To instantiate and use it directly, link it into your globals table via * To instantiate and use it directly, link it into your globals table via
* {@link Globals#load} using code such as: * {@link Globals#load} using code such as:
* *
* <pre> * <pre>
* { * {
* &#64;code * &#64;code
@@ -73,7 +73,7 @@ import org.luaj.vm2.lib.VarArgFunction;
* } * }
* </pre> * </pre>
* <p> * <p>
* *
* The {@code luajava} library is available on all JSE platforms via the call to * 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 * {@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 * 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> * <p>
* This has been implemented to match as closely as possible the behavior in the * This has been implemented to match as closely as possible the behavior in the
* corresponding library in C. * corresponding library in C.
* *
* @see LibFunction * @see LibFunction
* @see org.luaj.vm2.lib.jse.JsePlatform * @see org.luaj.vm2.lib.jse.JsePlatform
* @see org.luaj.vm2.lib.jme.JmePlatform * @see org.luaj.vm2.lib.jme.JmePlatform
@@ -108,6 +108,7 @@ public class LuajavaLib extends VarArgFunction {
public LuajavaLib() { public LuajavaLib() {
} }
@Override
public Varargs invoke(Varargs args) { public Varargs invoke(Varargs args) {
try { try {
switch (opcode) { switch (opcode) {
@@ -129,8 +130,8 @@ public class LuajavaLib extends VarArgFunction {
case NEW: { case NEW: {
// get constructor // get constructor
final LuaValue c = args.checkvalue(1); final LuaValue c = args.checkvalue(1);
final Class clazz = (opcode == NEWINSTANCE? classForName(c.tojstring()) final Class clazz = opcode == NEWINSTANCE? classForName(c.tojstring())
: (Class) c.checkuserdata(Class.class)); : (Class) c.checkuserdata(Class.class);
final Varargs consargs = args.subargs(2); final Varargs consargs = args.subargs(2);
return JavaClass.forClass(clazz).getConstructor().invoke(consargs); return JavaClass.forClass(clazz).getConstructor().invoke(consargs);
} }
@@ -160,8 +161,8 @@ public class LuajavaLib extends VarArgFunction {
String classname = args.checkjstring(1); String classname = args.checkjstring(1);
String methodname = args.checkjstring(2); String methodname = args.checkjstring(2);
Class clazz = classForName(classname); Class clazz = classForName(classname);
Method method = clazz.getMethod(methodname, new Class[] {}); Method method = clazz.getMethod(methodname);
Object result = method.invoke(clazz, new Object[] {}); Object result = method.invoke(clazz);
if (result instanceof LuaValue) { if (result instanceof LuaValue) {
return (LuaValue) result; return (LuaValue) result;
} else { } else {
@@ -192,12 +193,13 @@ public class LuajavaLib extends VarArgFunction {
this.lobj = lobj; this.lobj = lobj;
} }
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
String name = method.getName(); String name = method.getName();
LuaValue func = lobj.get(name); LuaValue func = lobj.get(name);
if (func.isnil()) if (func.isnil())
return null; 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; int n = args != null? args.length: 0;
LuaValue[] v; LuaValue[] v;
if (isvarargs) { if (isvarargs) {

View File

@@ -1,5 +1,5 @@
/** /**
* *
*/ */
package org.luaj.vm2.luajc; package org.luaj.vm2.luajc;
@@ -18,9 +18,10 @@ public class BasicBlock {
this.pc0 = this.pc1 = pc0; this.pc0 = this.pc1 = pc0;
} }
@Override
public String toString() { public String toString() {
StringBuffer sb = new StringBuffer(); 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"); + (next != null? " nxt: " + str(next, 0): "") + "\n");
return sb.toString(); return sb.toString();
} }
@@ -82,6 +83,7 @@ public class BasicBlock {
this.blocks = blocks; this.blocks = blocks;
} }
@Override
public void visitBranch(int pc0, int pc1) { public void visitBranch(int pc0, int pc1) {
if (blocks[pc0].next == null) if (blocks[pc0].next == null)
blocks[pc0].next = new BasicBlock[nnext[pc0]]; blocks[pc0].next = new BasicBlock[nnext[pc0]];
@@ -102,6 +104,7 @@ public class BasicBlock {
this.nprev = nprev; this.nprev = nprev;
} }
@Override
public void visitBranch(int pc0, int pc1) { public void visitBranch(int pc0, int pc1) {
nnext[pc0]++; nnext[pc0]++;
nprev[pc1]++; nprev[pc1]++;
@@ -116,11 +119,13 @@ public class BasicBlock {
this.isend = isend; this.isend = isend;
} }
@Override
public void visitBranch(int pc0, int pc1) { public void visitBranch(int pc0, int pc1) {
isend[pc0] = true; isend[pc0] = true;
isbeg[pc1] = true; isbeg[pc1] = true;
} }
@Override
public void visitReturn(int pc) { public void visitReturn(int pc) {
isend[pc] = true; isend[pc] = true;
} }

View File

@@ -10,7 +10,7 @@
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -177,11 +177,9 @@ public class JavaBuilder {
superclassType = p.numparams; superclassType = p.numparams;
if (p.is_vararg != 0 || superclassType >= SUPERTYPE_VARARGS) if (p.is_vararg != 0 || superclassType >= SUPERTYPE_VARARGS)
superclassType = SUPERTYPE_VARARGS; superclassType = SUPERTYPE_VARARGS;
for (int i = 0, n = p.code.length; i < n; i++) { for (int inst : p.code) {
int inst = p.code[i];
int o = Lua.GET_OPCODE(inst); int o = Lua.GET_OPCODE(inst);
if ((o == Lua.OP_TAILCALL) if (o == Lua.OP_TAILCALL || o == Lua.OP_RETURN && (Lua.GETARG_B(inst) < 1 || Lua.GETARG_B(inst) > 2)) {
|| ((o == Lua.OP_RETURN) && (Lua.GETARG_B(inst) < 1 || Lua.GETARG_B(inst) > 2))) {
superclassType = SUPERTYPE_VARARGS; superclassType = SUPERTYPE_VARARGS;
break; break;
} }
@@ -244,7 +242,7 @@ public class JavaBuilder {
} else { } else {
// fixed arg function between 0 and 3 arguments // fixed arg function between 0 and 3 arguments
for (slot = 0; slot < p.numparams; slot++) { 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)) { if (pi.isUpvalueCreate(-1, slot)) {
append(new ALOAD(1+slot)); append(new ALOAD(1+slot));
storeLocal(-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 // TODO: remove this for lua 5.2, not needed
for (; slot < p.maxstacksize; slot++) { for (; slot < p.maxstacksize; slot++) {
if (pi.isInitialValueUsed(slot)) { if (pi.isInitialValueUsed(slot)) {
@@ -264,7 +262,7 @@ public class JavaBuilder {
public byte[] completeClass(boolean genmain) { public byte[] completeClass(boolean genmain) {
// add class initializer // add class initializer
if (!init.isEmpty()) { if (!init.isEmpty()) {
MethodGen mg = new MethodGen(Constants.ACC_STATIC, Type.VOID, ARG_TYPES_NONE, new String[] {}, "<clinit>", MethodGen mg = new MethodGen(Constants.ACC_STATIC, Type.VOID, ARG_TYPES_NONE, new String[] {}, "<clinit>",
cg.getClassName(), init, cg.getConstantPool()); cg.getClassName(), init, cg.getConstantPool());
@@ -283,7 +281,7 @@ public class JavaBuilder {
cg.addMethod(mg.getMethod()); cg.addMethod(mg.getMethod());
main.dispose(); 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) { if (p.upvalues.length == 1 && superclassType == SUPERTYPE_VARARGS) {
MethodGen mg = new MethodGen(Constants.ACC_PUBLIC | Constants.ACC_FINAL, // access flags MethodGen mg = new MethodGen(Constants.ACC_PUBLIC | Constants.ACC_FINAL, // access flags
Type.VOID, // return type Type.VOID, // return type
@@ -307,7 +305,7 @@ public class JavaBuilder {
main.dispose(); 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) { if (genmain) {
MethodGen mg = new MethodGen(Constants.ACC_PUBLIC | Constants.ACC_STATIC, // access flags MethodGen mg = new MethodGen(Constants.ACC_PUBLIC | Constants.ACC_STATIC, // access flags
Type.VOID, // return type Type.VOID, // return type
@@ -355,22 +353,22 @@ public class JavaBuilder {
} }
public void loadBoolean(boolean b) { 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)); append(factory.createFieldAccess(STR_LUAVALUE, field, TYPE_LUABOOLEAN, Constants.GETSTATIC));
} }
private Map<Integer, Integer> plainSlotVars = new HashMap<Integer, Integer>(); private final Map<Integer, Integer> plainSlotVars = new HashMap<>();
private Map<Integer, Integer> upvalueSlotVars = new HashMap<Integer, Integer>(); private final Map<Integer, Integer> upvalueSlotVars = new HashMap<>();
private Map<Integer, LocalVariableGen> localVarGenBySlot = new HashMap<Integer, LocalVariableGen>(); private final Map<Integer, LocalVariableGen> localVarGenBySlot = new HashMap<>();
private int findSlot(int slot, Map<Integer, Integer> map, String prefix, Type type) { 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)) if (map.containsKey(islot))
return ((Integer) map.get(islot)).intValue(); return map.get(islot).intValue();
String name = prefix+slot; String name = prefix+slot;
LocalVariableGen local = mg.addLocalVariable(name, type, null, null); LocalVariableGen local = mg.addLocalVariable(name, type, null, null);
int index = local.getIndex(); int index = local.getIndex();
map.put(islot, Integer.valueOf(index)); map.put(islot, index);
localVarGenBySlot.put(islot, local); localVarGenBySlot.put(islot, local);
return index; return index;
} }
@@ -727,7 +725,7 @@ public class JavaBuilder {
append(factory.createFieldAccess(protoname, destname, uptype, Constants.PUTFIELD)); 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) { public void loadConstant(LuaValue value) {
switch (value.type()) { switch (value.type()) {
@@ -739,7 +737,7 @@ public class JavaBuilder {
break; break;
case LuaValue.TNUMBER: case LuaValue.TNUMBER:
case LuaValue.TSTRING: case LuaValue.TSTRING:
String name = (String) constants.get(value); String name = constants.get(value);
if (name == null) { if (name == null) {
name = value.type() == LuaValue.TNUMBER? value.isinttype()? createLuaIntegerField(value.checkint()) name = value.type() == LuaValue.TNUMBER? value.isinttype()? createLuaIntegerField(value.checkint())
: createLuaDoubleField(value.checkdouble()): createLuaStringField(value.checkstring()); : createLuaDoubleField(value.checkdouble()): createLuaStringField(value.checkstring());
@@ -786,7 +784,7 @@ public class JavaBuilder {
} else { } else {
char[] c = new char[ls.m_length]; char[] c = new char[ls.m_length];
for (int j = 0; j < ls.m_length; j++) 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(new PUSH(cp, new String(c)));
init.append( init.append(
factory.createInvoke(STR_STRING, "toCharArray", TYPE_CHARARRAY, Type.NO_ARGS, Constants.INVOKEVIRTUAL)); 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) { 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)) { if (localVarGenBySlot.containsKey(islot)) {
name = name.replaceAll("[^a-zA-Z0-9]", "_"); name = name.replaceAll("[^a-zA-Z0-9]", "_");
LocalVariableGen l = (LocalVariableGen) localVarGenBySlot.get(islot); LocalVariableGen l = localVarGenBySlot.get(islot);
l.setEnd(lastInstrHandles[end_pc-1]); l.setEnd(lastInstrHandles[end_pc-1]);
if (start_pc > 1) if (start_pc > 1)
l.setStart(lastInstrHandles[start_pc-2]); l.setStart(lastInstrHandles[start_pc-2]);
@@ -908,7 +906,7 @@ public class JavaBuilder {
public void closeUpvalue(int pc, int upindex) { public void closeUpvalue(int pc, int upindex) {
// TODO: assign the upvalue location the value null; // 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.THIS);
append(InstructionConstants.ACONST_NULL); append(InstructionConstants.ACONST_NULL);
if ( isrw ) { if ( isrw ) {

View File

@@ -10,7 +10,7 @@
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -66,9 +66,7 @@ public class JavaGen {
Prototype p = pi.prototype; Prototype p = pi.prototype;
int vresultbase = -1; int vresultbase = -1;
for (int bi = 0; bi < pi.blocklist.length; bi++) { for (BasicBlock b0 : pi.blocklist) {
BasicBlock b0 = pi.blocklist[bi];
// convert upvalues that are phi-variables // convert upvalues that are phi-variables
for (int slot = 0; slot < p.maxstacksize; slot++) { for (int slot = 0; slot < p.maxstacksize; slot++) {
int pc = b0.pc0; int pc = b0.pc0;
@@ -216,19 +214,19 @@ public class JavaGen {
loadLocalOrConstant(p, builder, pc, b); loadLocalOrConstant(p, builder, pc, b);
loadLocalOrConstant(p, builder, pc, c); loadLocalOrConstant(p, builder, pc, c);
builder.compareop(o); 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; break;
case Lua.OP_TEST: /* A C if not (R(A) <=> C) then pc++ */ case Lua.OP_TEST: /* A C if not (R(A) <=> C) then pc++ */
builder.loadLocal(pc, a); builder.loadLocal(pc, a);
builder.toBoolean(); 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; break;
case Lua.OP_TESTSET: /* A B C if (R(B) <=> C) then R(A):= R(B) else pc++ */ case Lua.OP_TESTSET: /* A B C if (R(B) <=> C) then R(A):= R(B) else pc++ */
builder.loadLocal(pc, b); builder.loadLocal(pc, b);
builder.toBoolean(); 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.loadLocal(pc, b);
builder.storeLocal(pc, a); builder.storeLocal(pc, a);
break; break;

View File

@@ -19,7 +19,7 @@ import org.luaj.vm2.Prototype;
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * 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 { public class JavaLoader extends ClassLoader {
private Map<String, byte[]> unloaded = new HashMap<String, byte[]>(); private final Map<String, byte[]> unloaded = new HashMap<>();
public JavaLoader() { public JavaLoader() {
} }
@@ -63,8 +63,9 @@ public class JavaLoader extends ClassLoader {
include(jg.inners[i]); include(jg.inners[i]);
} }
@Override
public Class findClass(String classname) throws ClassNotFoundException { public Class findClass(String classname) throws ClassNotFoundException {
byte[] bytes = (byte[]) unloaded.get(classname); byte[] bytes = unloaded.get(classname);
if (bytes != null) if (bytes != null)
return defineClass(classname, bytes, 0, bytes.length); return defineClass(classname, bytes, 0, bytes.length);
return super.findClass(classname); return super.findClass(classname);

View File

@@ -10,7 +10,7 @@
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -44,7 +44,7 @@ import org.luaj.vm2.compiler.LuaC;
* <p> * <p>
* To override the default compiling behavior with {@link LuaJC} lua-to-java * To override the default compiling behavior with {@link LuaJC} lua-to-java
* bytecode compiler, install it before undumping code, for example: * bytecode compiler, install it before undumping code, for example:
* *
* <pre> * <pre>
* {@code * {@code
* LuaValue globals = JsePlatform.standardGlobals(); * 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. * 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 * If the library is not found, the default {@link LuaC} lua-to-lua-bytecode
* compiler will be used. * compiler will be used.
* *
* @see Globals#compiler * @see Globals#compiler
* @see #install(Globals) * @see #install(Globals)
* @see org.luaj.vm2.compiler.LuaC * @see org.luaj.vm2.compiler.LuaC
@@ -107,6 +107,7 @@ public class LuaJC implements Globals.Loader {
insert(h, gen.inners[i]); insert(h, gen.inners[i]);
} }
@Override
public LuaFunction load(Prototype p, String name, LuaValue globals) throws IOException { public LuaFunction load(Prototype p, String name, LuaValue globals) throws IOException {
String luaname = toStandardLuaFileName(name); String luaname = toStandardLuaFileName(name);
String classname = toStandardJavaClassName(luaname); String classname = toStandardJavaClassName(luaname);
@@ -120,8 +121,7 @@ public class LuaJC implements Globals.Loader {
for (int i = 0, n = stub.length(); i < n; ++i) { for (int i = 0, n = stub.length(); i < n; ++i) {
final char c = stub.charAt(i); final char c = stub.charAt(i);
classname.append( 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(); return classname.toString();
} }
@@ -133,7 +133,6 @@ public class LuaJC implements Globals.Loader {
} }
private static String toStub(String s) { private static String toStub(String s) {
String stub = s.endsWith(".lua")? s.substring(0, s.length()-4): s; return s.endsWith(".lua")? s.substring(0, s.length()-4): s;
return stub;
} }
} }

View File

@@ -57,6 +57,7 @@ public class ProtoInfo {
findUpvalues(); findUpvalues();
} }
@Override
public String toString() { public String toString() {
StringBuffer sb = new StringBuffer(); StringBuffer sb = new StringBuffer();
@@ -64,12 +65,11 @@ public class ProtoInfo {
sb.append("proto '" + name + "'\n"); sb.append("proto '" + name + "'\n");
// upvalues from outer scopes // 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"); sb.append(" up[" + i + "]: " + upvals[i] + "\n");
// basic blocks // basic blocks
for (int i = 0; i < blocklist.length; i++) { for (BasicBlock b : blocklist) {
BasicBlock b = blocklist[i];
int pc0 = b.pc0; int pc0 = b.pc0;
sb.append(" block " + b.toString()); sb.append(" block " + b.toString());
appendOpenUps(sb, -1); appendOpenUps(sb, -1);
@@ -84,9 +84,9 @@ public class ProtoInfo {
sb.append(" "); sb.append(" ");
for (int j = 0; j < prototype.maxstacksize; j++) { for (int j = 0; j < prototype.maxstacksize; j++) {
VarInfo v = vars[j][pc]; VarInfo v = vars[j][pc];
String u = (v == null? "" String u = v == null? ""
: v.upvalue != null? !v.upvalue.rw? "[C] ": (v.allocupvalue && v.pc == pc? "[*] ": "[] ") : v.upvalue != null? !v.upvalue.rw? "[C] ": v.allocupvalue && v.pc == pc? "[*] ": "[] "
: " "); : " ";
String s = v == null? "null ": String.valueOf(v); String s = v == null? "null ": String.valueOf(v);
sb.append(s+u); sb.append(s+u);
} }
@@ -115,7 +115,7 @@ public class ProtoInfo {
private void appendOpenUps(StringBuffer sb, int pc) { private void appendOpenUps(StringBuffer sb, int pc) {
for (int j = 0; j < prototype.maxstacksize; j++) { 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) { if (v != null && v.pc == pc && v.allocupvalue) {
sb.append(" open: " + v.upvalue + "\n"); sb.append(" open: " + v.upvalue + "\n");
} }
@@ -132,8 +132,8 @@ public class ProtoInfo {
v[i] = new VarInfo[n]; v[i] = new VarInfo[n];
// process instructions // process instructions
for (int bi = 0; bi < blocklist.length; bi++) { for (BasicBlock element : blocklist) {
BasicBlock b0 = blocklist[bi]; BasicBlock b0 = element;
// input from previous blocks // input from previous blocks
int nprev = b0.prev != null? b0.prev.length: 0; int nprev = b0.prev != null? b0.prev.length: 0;
@@ -399,8 +399,7 @@ public class ProtoInfo {
} }
private void replaceTrivialPhiVariables() { private void replaceTrivialPhiVariables() {
for (int i = 0; i < blocklist.length; i++) { for (BasicBlock b0 : blocklist) {
BasicBlock b0 = blocklist[i];
for (int slot = 0; slot < prototype.maxstacksize; slot++) { for (int slot = 0; slot < prototype.maxstacksize; slot++) {
VarInfo vold = vars[slot][b0.pc0]; VarInfo vold = vars[slot][b0.pc0];
VarInfo vnew = vold.resolvePhiVariableValues(); VarInfo vnew = vold.resolvePhiVariableValues();

View File

@@ -1,5 +1,5 @@
/** /**
* *
*/ */
package org.luaj.vm2.luajc; package org.luaj.vm2.luajc;
@@ -60,8 +60,7 @@ public class UpvalInfo {
private boolean includePosteriorVarsCheckLoops(VarInfo prior) { private boolean includePosteriorVarsCheckLoops(VarInfo prior) {
boolean loopDetected = false; boolean loopDetected = false;
for (int i = 0, n = pi.blocklist.length; i < n; i++) { for (BasicBlock b : pi.blocklist) {
BasicBlock b = pi.blocklist[i];
VarInfo v = pi.vars[slot][b.pc1]; VarInfo v = pi.vars[slot][b.pc1];
if (v == prior) { if (v == prior) {
for (int j = 0, m = b.next != null? b.next.length: 0; j < m; j++) { 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) { private void includePriorVarsIgnoreLoops(VarInfo poster) {
for (int i = 0, n = pi.blocklist.length; i < n; i++) { for (BasicBlock b : pi.blocklist) {
BasicBlock b = pi.blocklist[i];
VarInfo v = pi.vars[slot][b.pc0]; VarInfo v = pi.vars[slot][b.pc0];
if (v == poster) { if (v == poster) {
for (int j = 0, m = b.prev != null? b.prev.length: 0; j < m; j++) { 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; var[nvars++] = v;
} }
@Override
public String toString() { public String toString() {
StringBuffer sb = new StringBuffer(); StringBuffer sb = new StringBuffer();
sb.append(pi.name); sb.append(pi.name);
@@ -141,8 +140,8 @@ public class UpvalInfo {
if (v != null && v.upvalue != this) if (v != null && v.upvalue != this)
return true; return true;
} else { } else {
for (int i = 0, n = b.prev.length; i < n; i++) { for (BasicBlock element : b.prev) {
v = pi.vars[slot][b.prev[i].pc1]; v = pi.vars[slot][element.pc1];
if (v != null && v.upvalue != this) if (v != null && v.upvalue != this)
return true; return true;
} }

View File

@@ -1,5 +1,5 @@
/** /**
* *
*/ */
package org.luaj.vm2.luajc; package org.luaj.vm2.luajc;
@@ -37,15 +37,16 @@ public class VarInfo {
this.pc = pc; this.pc = pc;
} }
@Override
public String toString() { 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, * Return replacement variable if there is exactly one value possible,
* otherwise compute entire collection of variables and return null. * otherwise compute entire collection of variables and return null.
* Computes the list of aall variable values, and saves it for the future. * 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 * @return new Variable to replace with if there is only one value, or null
* to leave alone. * to leave alone.
*/ */
@@ -64,6 +65,7 @@ public class VarInfo {
super(slot, pc); super(slot, pc);
} }
@Override
public String toString() { public String toString() {
return slot + ".p"; return slot + ".p";
} }
@@ -74,6 +76,7 @@ public class VarInfo {
super(slot, pc); super(slot, pc);
} }
@Override
public String toString() { public String toString() {
return "nil"; return "nil";
} }
@@ -88,13 +91,15 @@ public class VarInfo {
this.pi = pi; this.pi = pi;
} }
@Override
public boolean isPhiVar() { return true; } public boolean isPhiVar() { return true; }
@Override
public String toString() { public String toString() {
StringBuffer sb = new StringBuffer(); StringBuffer sb = new StringBuffer();
sb.append(super.toString()); sb.append(super.toString());
sb.append("={"); 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) if (i > 0)
sb.append(","); sb.append(",");
sb.append(String.valueOf(values[i])); sb.append(String.valueOf(values[i]));
@@ -103,6 +108,7 @@ public class VarInfo {
return sb.toString(); return sb.toString();
} }
@Override
public VarInfo resolvePhiVariableValues() { public VarInfo resolvePhiVariableValues() {
Set visitedBlocks = new HashSet(); Set visitedBlocks = new HashSet();
Set vars = new HashSet(); Set vars = new HashSet();
@@ -124,6 +130,7 @@ public class VarInfo {
return null; return null;
} }
@Override
protected void collectUniqueValues(Set visitedBlocks, Set vars) { protected void collectUniqueValues(Set visitedBlocks, Set vars) {
BasicBlock b = pi.blocks[pc]; BasicBlock b = pi.blocks[pc];
if (pc == 0) if (pc == 0)

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