Remove libs dependency from PackageLib.

This commit is contained in:
Enyby
2019-01-13 19:23:44 +02:00
parent 6f5af581e8
commit 9688d3c5fc
9 changed files with 326 additions and 326 deletions

View File

@@ -27,15 +27,15 @@ import org.luaj.vm2.Varargs;
/** /**
* Subclass of LibFunction that implements the Lua standard {@code bit32} library. * Subclass of LibFunction that implements the Lua standard {@code bit32} 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.jme.JmePlatform#standardGlobals()} * {@link org.luaj.vm2.lib.jse.JsePlatform#standardGlobals()} or {@link org.luaj.vm2.lib.jme.JmePlatform#standardGlobals()}
* <pre> {@code * <pre> {@code
* Globals globals = JsePlatform.standardGlobals(); * Globals globals = JsePlatform.standardGlobals();
* System.out.println( globals.get("bit32").get("bnot").call( LuaValue.valueOf(2) ) ); * System.out.println( globals.get("bit32").get("bnot").call( LuaValue.valueOf(2) ) );
* } </pre> * } </pre>
* <p> * <p>
* To instantiate and use it directly, * To instantiate and use it directly,
* link it into your globals table via {@link LuaValue#load(LuaValue)} using code such as: * link it into your globals table via {@link LuaValue#load(LuaValue)} using code such as:
* <pre> {@code * <pre> {@code
* Globals globals = new Globals(); * Globals globals = new Globals();
@@ -71,7 +71,7 @@ public class Bit32Lib extends TwoArgFunction {
"arshift", "lrotate", "lshift", "rrotate", "rshift" "arshift", "lrotate", "lshift", "rrotate", "rshift"
}); });
env.set("bit32", t); env.set("bit32", t);
env.get("package").get("loaded").set("bit32", t); if (!env.get("package").isnil()) env.get("package").get("loaded").set("bit32", t);
return t; return t;
} }
@@ -219,6 +219,6 @@ public class Bit32Lib extends TwoArgFunction {
} }
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((double) ((long) x & 0xFFFFFFFFL)) : valueOf(x);
} }
} }

View File

@@ -27,25 +27,25 @@ import org.luaj.vm2.LuaThread;
import org.luaj.vm2.LuaValue; import org.luaj.vm2.LuaValue;
import org.luaj.vm2.Varargs; import org.luaj.vm2.Varargs;
/** /**
* Subclass of {@link LibFunction} which implements the lua standard {@code coroutine} * Subclass of {@link LibFunction} which implements the lua standard {@code coroutine}
* library. * library.
* <p> * <p>
* The coroutine library in luaj has the same behavior as the * The coroutine library in luaj has the same behavior as the
* coroutine library in C, but is implemented using Java Threads to maintain * coroutine library in C, but is implemented using Java Threads to maintain
* the call state between invocations. Therefore it can be yielded from anywhere, * the call state between invocations. Therefore it can be yielded from anywhere,
* similar to the "Coco" yield-from-anywhere patch available for C-based lua. * similar to the "Coco" yield-from-anywhere patch available for C-based lua.
* However, coroutines that are yielded but never resumed to complete their execution * However, coroutines that are yielded but never resumed to complete their execution
* may not be collected by the garbage collector. * may not be collected by the garbage collector.
* <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.jme.JmePlatform#standardGlobals()} * {@link org.luaj.vm2.lib.jse.JsePlatform#standardGlobals()} or {@link org.luaj.vm2.lib.jme.JmePlatform#standardGlobals()}
* <pre> {@code * <pre> {@code
* Globals globals = JsePlatform.standardGlobals(); * Globals globals = JsePlatform.standardGlobals();
* System.out.println( globals.get("coroutine").get("running").call() ); * System.out.println( globals.get("coroutine").get("running").call() );
* } </pre> * } </pre>
* <p> * <p>
* To instantiate and use it directly, * To instantiate and use it directly,
* link it into your globals table via {@link LuaValue#load(LuaValue)} using code such as: * link it into your globals table via {@link LuaValue#load(LuaValue)} using code such as:
* <pre> {@code * <pre> {@code
* Globals globals = new Globals(); * Globals globals = new Globals();
@@ -82,7 +82,7 @@ public class CoroutineLib extends TwoArgFunction {
coroutine.set("yield", new yield()); coroutine.set("yield", new yield());
coroutine.set("wrap", new wrap()); coroutine.set("wrap", new wrap());
env.set("coroutine", coroutine); env.set("coroutine", coroutine);
env.get("package").get("loaded").set("coroutine", coroutine); if (!env.get("package").isnil()) env.get("package").get("loaded").set("coroutine", coroutine);
return coroutine; return coroutine;
} }

View File

@@ -38,26 +38,26 @@ import org.luaj.vm2.Print;
import org.luaj.vm2.Prototype; import org.luaj.vm2.Prototype;
import org.luaj.vm2.Varargs; import org.luaj.vm2.Varargs;
/** /**
* Subclass of {@link LibFunction} which implements the lua standard {@code debug} * Subclass of {@link LibFunction} which implements the lua standard {@code debug}
* library. * library.
* <p> * <p>
* The debug library in luaj tries to emulate the behavior of the corresponding C-based lua library. * The debug library in luaj tries to emulate the behavior of the corresponding C-based lua library.
* To do this, it must maintain a separate stack of calls to {@link LuaClosure} and {@link LibFunction} * To do this, it must maintain a separate stack of calls to {@link LuaClosure} and {@link LibFunction}
* instances. * instances.
* Especially when lua-to-java bytecode compiling is being used * Especially when lua-to-java bytecode compiling is being used
* via a {@link org.luaj.vm2.Globals.Compiler} such as {@link org.luaj.vm2.luajc.LuaJC}, * via a {@link org.luaj.vm2.Globals.Compiler} such as {@link org.luaj.vm2.luajc.LuaJC},
* this cannot be done in all cases. * this cannot be done in all cases.
* <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#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> {@code * <pre> {@code
* Globals globals = JsePlatform.debugGlobals(); * Globals globals = JsePlatform.debugGlobals();
* System.out.println( globals.get("debug").get("traceback").call() ); * System.out.println( globals.get("debug").get("traceback").call() );
* } </pre> * } </pre>
* <p> * <p>
* To instantiate and use it directly, * To instantiate and use it directly,
* link it into your globals table via {@link LuaValue#load(LuaValue)} using code such as: * link it into your globals table via {@link LuaValue#load(LuaValue)} using code such as:
* <pre> {@code * <pre> {@code
* Globals globals = new Globals(); * Globals globals = new Globals();
@@ -84,27 +84,27 @@ public class DebugLib extends TwoArgFunction {
try { TRACE = (null != System.getProperty("TRACE")); } catch (Exception e) {} try { TRACE = (null != System.getProperty("TRACE")); } catch (Exception e) {}
} }
static final LuaString LUA = valueOf("Lua"); static final LuaString LUA = valueOf("Lua");
private static final LuaString QMARK = valueOf("?"); private static final LuaString QMARK = valueOf("?");
private static final LuaString CALL = valueOf("call"); private static final LuaString CALL = valueOf("call");
private static final LuaString LINE = valueOf("line"); private static final LuaString LINE = valueOf("line");
private static final LuaString COUNT = valueOf("count"); private static final LuaString COUNT = valueOf("count");
private static final LuaString RETURN = valueOf("return"); private static final LuaString RETURN = valueOf("return");
static final LuaString FUNC = valueOf("func"); static final LuaString FUNC = valueOf("func");
static final LuaString ISTAILCALL = valueOf("istailcall"); static final LuaString ISTAILCALL = valueOf("istailcall");
static final LuaString ISVARARG = valueOf("isvararg"); static final LuaString ISVARARG = valueOf("isvararg");
static final LuaString NUPS = valueOf("nups"); static final LuaString NUPS = valueOf("nups");
static final LuaString NPARAMS = valueOf("nparams"); static final LuaString NPARAMS = valueOf("nparams");
static final LuaString NAME = valueOf("name"); static final LuaString NAME = valueOf("name");
static final LuaString NAMEWHAT = valueOf("namewhat"); static final LuaString NAMEWHAT = valueOf("namewhat");
static final LuaString WHAT = valueOf("what"); static final LuaString WHAT = valueOf("what");
static final LuaString SOURCE = valueOf("source"); static final LuaString SOURCE = valueOf("source");
static final LuaString SHORT_SRC = valueOf("short_src"); static final LuaString SHORT_SRC = valueOf("short_src");
static final LuaString LINEDEFINED = valueOf("linedefined"); static final LuaString LINEDEFINED = valueOf("linedefined");
static final LuaString LASTLINEDEFINED = valueOf("lastlinedefined"); static final LuaString LASTLINEDEFINED = valueOf("lastlinedefined");
static final LuaString CURRENTLINE = valueOf("currentline"); static final LuaString CURRENTLINE = valueOf("currentline");
static final LuaString ACTIVELINES = valueOf("activelines"); static final LuaString ACTIVELINES = valueOf("activelines");
Globals globals; Globals globals;
@@ -135,19 +135,19 @@ public class DebugLib extends TwoArgFunction {
debug.set("upvalueid", new upvalueid()); debug.set("upvalueid", new upvalueid());
debug.set("upvaluejoin", new upvaluejoin()); debug.set("upvaluejoin", new upvaluejoin());
env.set("debug", debug); env.set("debug", debug);
env.get("package").get("loaded").set("debug", debug); if (!env.get("package").isnil()) env.get("package").get("loaded").set("debug", debug);
return debug; return debug;
} }
// debug.debug() // debug.debug()
static final class debug extends ZeroArgFunction { static final class debug extends ZeroArgFunction {
public LuaValue call() { public LuaValue call() {
return NONE; return NONE;
} }
} }
// debug.gethook ([thread]) // debug.gethook ([thread])
final class gethook extends VarArgFunction { final class gethook extends VarArgFunction {
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;
@@ -159,10 +159,10 @@ 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 {
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;
LuaValue func = args.arg(a++); LuaValue func = args.arg(a++);
String what = args.optjstring(a++, "flnStu"); String what = args.optjstring(a++, "flnStu");
DebugLib.CallStack callstack = callstack(thread); DebugLib.CallStack callstack = callstack(thread);
@@ -222,10 +222,10 @@ 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 {
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;
int level = args.checkint(a++); int level = args.checkint(a++);
int local = args.checkint(a++); int local = args.checkint(a++);
CallFrame f = callstack(thread).getCallFrame(level); CallFrame f = callstack(thread).getCallFrame(level);
@@ -249,7 +249,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 {
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);
@@ -265,7 +265,7 @@ public class DebugLib extends TwoArgFunction {
} }
// debug.getuservalue (u) // debug.getuservalue (u)
static final class getuservalue extends LibFunction { static final class getuservalue extends LibFunction {
public LuaValue call(LuaValue u) { public LuaValue call(LuaValue u) {
return u.isuserdata()? u: NIL; return u.isuserdata()? u: NIL;
} }
@@ -273,10 +273,10 @@ 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 {
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;
LuaValue func = args.optfunction(a++, null); LuaValue func = args.optfunction(a++, null);
String str = args.optjstring(a++,""); String str = args.optjstring(a++,"");
int count = args.optint(a++,0); int count = args.optint(a++,0);
@@ -298,20 +298,20 @@ 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 {
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;
int level = args.checkint(a++); int level = args.checkint(a++);
int local = args.checkint(a++); int local = args.checkint(a++);
LuaValue value = args.arg(a++); LuaValue value = args.arg(a++);
CallFrame f = callstack(thread).getCallFrame(level); CallFrame f = callstack(thread).getCallFrame(level);
return f != null? f.setLocal(local, value): NONE; return f != null? f.setLocal(local, value): NONE;
} }
} }
// debug.setmetatable (value, table) // debug.setmetatable (value, table)
static final class setmetatable extends TwoArgFunction { static final class setmetatable extends TwoArgFunction {
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() ) {
@@ -328,7 +328,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 {
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);
@@ -346,7 +346,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 {
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);
@@ -358,10 +358,10 @@ 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 {
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;
String message = args.optjstring(a++, null); String message = args.optjstring(a++, null);
int level = args.optint(a++,1); int level = args.optint(a++,1);
String tb = callstack(thread).traceback(level); String tb = callstack(thread).traceback(level);
@@ -370,7 +370,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 {
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);
@@ -385,7 +385,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 {
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);
@@ -587,7 +587,7 @@ public class DebugLib extends TwoArgFunction {
if (frame[calls-i].f == func) if (frame[calls-i].f == func)
return frame[i]; return frame[i];
return null; return null;
} }
synchronized DebugInfo auxgetinfo(String what, LuaFunction f, CallFrame ci) { synchronized DebugInfo auxgetinfo(String what, LuaFunction f, CallFrame ci) {
@@ -641,7 +641,7 @@ public class DebugLib extends TwoArgFunction {
} }
} }
return ar; return ar;
} }
} }
@@ -694,7 +694,7 @@ public class DebugLib extends TwoArgFunction {
int currentline() { int currentline() {
if ( !f.isclosure() ) return -1; if ( !f.isclosure() ) return -1;
int[] li = f.checkclosure().p.lineinfo; int[] li = f.checkclosure().p.lineinfo;
return li==null || pc<0 || pc>=li.length? -1: li[pc]; return li==null || pc<0 || pc>=li.length? -1: li[pc];
} }
String sourceline() { String sourceline() {
if ( !f.isclosure() ) return f.tojstring(); if ( !f.isclosure() ) return f.tojstring();
@@ -721,7 +721,7 @@ public class DebugLib extends TwoArgFunction {
static void lua_assert(boolean x) { static void lua_assert(boolean x) {
if (!x) throw new RuntimeException("lua_assert failed"); if (!x) throw new RuntimeException("lua_assert failed");
} }
static class NameWhat { static class NameWhat {
final String name; final String name;

View File

@@ -31,31 +31,31 @@ import org.luaj.vm2.LuaTable;
import org.luaj.vm2.LuaValue; import org.luaj.vm2.LuaValue;
import org.luaj.vm2.Varargs; import org.luaj.vm2.Varargs;
/** /**
* Abstract base class extending {@link LibFunction} which implements the * Abstract base class extending {@link LibFunction} which implements the
* core of the lua standard {@code io} library. * core of the lua standard {@code io} library.
* <p> * <p>
* It contains the implementation of the io library support that is common to * It contains the implementation of the io library support that is common to
* the JSE and JME platforms. * the JSE and JME platforms.
* In practice on of the concrete IOLib subclasses is chosen: * In practice on of the concrete IOLib subclasses is chosen:
* {@link org.luaj.vm2.lib.jse.JseIoLib} for the JSE platform, and * {@link org.luaj.vm2.lib.jse.JseIoLib} for the JSE platform, and
* {@link org.luaj.vm2.lib.jme.JmeIoLib} for the JME platform. * {@link org.luaj.vm2.lib.jme.JmeIoLib} for the JME platform.
* <p> * <p>
* The JSE implementation conforms almost completely to the C-based lua library, * The JSE implementation conforms almost completely to the C-based lua library,
* while the JME implementation follows closely except in the area of random-access files, * while the JME implementation follows closely except in the area of random-access files,
* which are difficult to support properly on JME. * which are difficult to support properly on JME.
* <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.jme.JmePlatform#standardGlobals()} * {@link org.luaj.vm2.lib.jse.JsePlatform#standardGlobals()} or {@link org.luaj.vm2.lib.jme.JmePlatform#standardGlobals()}
* <pre> {@code * <pre> {@code
* Globals globals = JsePlatform.standardGlobals(); * Globals globals = JsePlatform.standardGlobals();
* 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} library will be loaded, which will include * In this example the platform-specific {@link org.luaj.vm2.lib.jse.JseIoLib} library will be loaded, which will include
* the base functionality provided by this class, whereas the {@link org.luaj.vm2.lib.jse.JsePlatform} would load the * the base functionality provided by this class, whereas the {@link org.luaj.vm2.lib.jse.JsePlatform} would load the
* {@link org.luaj.vm2.lib.jse.JseIoLib}. * {@link org.luaj.vm2.lib.jse.JseIoLib}.
* <p> * <p>
* To instantiate and use it directly, * To instantiate and use it directly,
* link it into your globals table via {@link LuaValue#load(LuaValue)} using code such as: * link it into your globals table via {@link LuaValue#load(LuaValue)} using code such as:
* <pre> {@code * <pre> {@code
* Globals globals = new Globals(); * Globals globals = new Globals();
@@ -73,10 +73,10 @@ import org.luaj.vm2.Varargs;
* @see org.luaj.vm2.lib.jme.JmeIoLib * @see org.luaj.vm2.lib.jme.JmeIoLib
* @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> * @see <a href="http://www.lua.org/manual/5.1/manual.html#5.7">http://www.lua.org/manual/5.1/manual.html#5.7</a>
*/ */
abstract abstract
public class IoLib extends TwoArgFunction { public class IoLib extends TwoArgFunction {
abstract abstract
protected class File extends LuaValue{ protected class File extends LuaValue{
abstract public void write( LuaString string ) throws IOException; abstract public void write( LuaString string ) throws IOException;
abstract public void flush() throws IOException; abstract public void flush() throws IOException;
@@ -85,12 +85,12 @@ public class IoLib extends TwoArgFunction {
abstract public boolean isclosed(); abstract public boolean isclosed();
// returns new position // returns new position
abstract public int seek(String option, int bytecount) throws IOException; abstract public int seek(String option, int bytecount) throws IOException;
abstract public void setvbuf(String mode, int size); abstract public void setvbuf(String mode, int size);
// get length remaining to read // get length remaining to read
abstract public int remaining() throws IOException; abstract public int remaining() throws IOException;
// peek ahead one character // peek ahead one character
abstract public int peek() throws IOException, EOFException; abstract public 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; abstract public 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; abstract public int read(byte[] bytes, int offset, int length) throws IOException;
@@ -123,29 +123,29 @@ public class IoLib extends TwoArgFunction {
/** Enumerated value representing a file type for a named file */ /** Enumerated value representing a file type for a named file */
protected static final int FTYPE_NAMED = 3; protected static final int FTYPE_NAMED = 3;
/** /**
* Wrap the standard input. * Wrap the standard input.
* @return File * @return File
* @throws IOException * @throws IOException
*/ */
abstract protected File wrapStdin() throws IOException; abstract protected File wrapStdin() throws IOException;
/** /**
* Wrap the standard output. * Wrap the standard output.
* @return File * @return File
* @throws IOException * @throws IOException
*/ */
abstract protected File wrapStdout() throws IOException; abstract protected File wrapStdout() throws IOException;
/** /**
* Wrap the standard error output. * Wrap the standard error output.
* @return File * @return File
* @throws IOException * @throws IOException
*/ */
abstract protected File wrapStderr() throws IOException; abstract protected File wrapStderr() throws IOException;
/** /**
* 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
@@ -157,7 +157,7 @@ public class IoLib extends TwoArgFunction {
abstract protected File openFile( String filename, boolean readMode, boolean appendMode, boolean updateMode, boolean binaryMode ) throws IOException; abstract protected File openFile( String filename, boolean readMode, boolean appendMode, boolean updateMode, boolean binaryMode ) throws IOException;
/** /**
* 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
*/ */
@@ -167,7 +167,7 @@ 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
* @throws IOException if an i/o exception occurs * @throws IOException if an i/o exception occurs
*/ */
abstract protected File openProgram(String prog, String mode) throws IOException; abstract protected File openProgram(String prog, String mode) throws IOException;
@@ -178,7 +178,7 @@ public class IoLib extends TwoArgFunction {
private static final LuaValue STDIN = valueOf("stdin"); private static final LuaValue STDIN = valueOf("stdin");
private static final LuaValue STDOUT = valueOf("stdout"); private static final LuaValue STDOUT = valueOf("stdout");
private static final LuaValue STDERR = valueOf("stderr"); private static final LuaValue STDERR = valueOf("stderr");
private static final LuaValue FILE = valueOf("file"); private static final LuaValue FILE = valueOf("file");
private static final LuaValue CLOSED_FILE = valueOf("closed file"); private static final LuaValue CLOSED_FILE = valueOf("closed file");
@@ -256,7 +256,7 @@ public class IoLib extends TwoArgFunction {
// return the table // return the table
env.set("io", t); env.set("io", t);
env.get("package").get("loaded").set("io", t); if (!env.get("package").isnil()) env.get("package").get("loaded").set("io", t);
return t; return t;
} }
@@ -316,7 +316,7 @@ public class IoLib extends TwoArgFunction {
return infile!=null? infile: (infile=ioopenfile(FTYPE_STDIN, "-","r")); return infile!=null? infile: (infile=ioopenfile(FTYPE_STDIN, "-","r"));
} }
// io.flush() -> bool // io.flush() -> bool
public Varargs _io_flush() throws IOException { public Varargs _io_flush() throws IOException {
checkopen(output()); checkopen(output());
outfile.flush(); outfile.flush();
@@ -337,7 +337,7 @@ public class IoLib extends TwoArgFunction {
// io.input([file]) -> file // io.input([file]) -> file
public Varargs _io_input(LuaValue file) { public Varargs _io_input(LuaValue file) {
infile = file.isnil()? input(): infile = file.isnil()? input():
file.isstring()? ioopenfile(FTYPE_NAMED, file.checkjstring(),"r"): file.isstring()? ioopenfile(FTYPE_NAMED, file.checkjstring(),"r"):
checkfile(file); checkfile(file);
return infile; return infile;
@@ -345,7 +345,7 @@ public class IoLib extends TwoArgFunction {
// io.output(filename) -> file // io.output(filename) -> file
public Varargs _io_output(LuaValue filename) { public Varargs _io_output(LuaValue filename) {
outfile = filename.isnil()? output(): outfile = filename.isnil()? output():
filename.isstring()? ioopenfile(FTYPE_NAMED, filename.checkjstring(),"w"): filename.isstring()? ioopenfile(FTYPE_NAMED, filename.checkjstring(),"w"):
checkfile(filename); checkfile(filename);
return outfile; return outfile;
@@ -420,7 +420,7 @@ public class IoLib extends TwoArgFunction {
return valueOf( checkfile(file).seek(whence,offset) ); return valueOf( checkfile(file).seek(whence,offset) );
} }
// file:write(...) -> void // file:write(...) -> void
public Varargs _file_write(LuaValue file, Varargs subargs) throws IOException { public Varargs _file_write(LuaValue file, Varargs subargs) throws IOException {
return iowrite(checkfile(file),subargs); return iowrite(checkfile(file),subargs);
} }
@@ -468,7 +468,7 @@ public class IoLib extends TwoArgFunction {
} }
static Varargs errorresult(Exception ioe) { static Varargs errorresult(Exception ioe) {
String s = ioe.getMessage(); String s = ioe.getMessage();
return errorresult("io error: "+(s!=null? s: ioe.toString())); return errorresult("io error: "+(s!=null? s: ioe.toString()));
} }
@@ -509,8 +509,8 @@ public class IoLib extends TwoArgFunction {
case 'a': vi = freadall(f); break item; case 'a': vi = freadall(f); break item;
} }
} }
default: default:
return argerror( i+1, "(invalid format)" ); return argerror( i+1, "(invalid format)" );
} }
if ( (v[i++] = vi).isnil() ) if ( (v[i++] = vi).isnil() )
break; break;
@@ -564,7 +564,7 @@ public class IoLib extends TwoArgFunction {
int c; int c;
try { try {
if ( lineonly ) { if ( lineonly ) {
loop: while ( (c = f.read()) > 0 ) { loop: while ( (c = f.read()) > 0 ) {
switch ( c ) { switch ( c ) {
case '\r': break; case '\r': break;
case '\n': break loop; case '\n': break loop;
@@ -572,13 +572,13 @@ public class IoLib extends TwoArgFunction {
} }
} }
} else { } else {
while ( (c = f.read()) > 0 ) while ( (c = f.read()) > 0 )
baos.write(c); baos.write(c);
} }
} catch ( EOFException e ) { } catch ( EOFException e ) {
c = -1; c = -1;
} }
return ( c < 0 && baos.size() == 0 )? return ( c < 0 && baos.size() == 0 )?
(LuaValue) NIL: (LuaValue) NIL:
(LuaValue) LuaString.valueUsing(baos.toByteArray()); (LuaValue) LuaString.valueUsing(baos.toByteArray());
} }
@@ -619,7 +619,7 @@ public class IoLib extends TwoArgFunction {
if ( baos != null ) if ( baos != null )
baos.write( c ); baos.write( c );
} }
} }

View File

@@ -28,13 +28,13 @@ import org.luaj.vm2.LuaTable;
import org.luaj.vm2.LuaValue; import org.luaj.vm2.LuaValue;
import org.luaj.vm2.Varargs; import org.luaj.vm2.Varargs;
/** /**
* Subclass of {@link LibFunction} which implements the lua standard {@code math} * Subclass of {@link LibFunction} which implements the lua standard {@code math}
* library. * library.
* <p> * <p>
* It contains only the math library support that is possible on JME. * It contains only the math library support that is possible on JME.
* For a more complete implementation based on math functions specific to JSE * For a more complete implementation based on math functions specific to JSE
* use {@link org.luaj.vm2.lib.jse.JseMathLib}. * use {@link org.luaj.vm2.lib.jse.JseMathLib}.
* In Particular the following math functions are <b>not</b> implemented by this library: * In Particular the following math functions are <b>not</b> implemented by this library:
* <ul> * <ul>
* <li>acos</li> * <li>acos</li>
@@ -47,21 +47,21 @@ import org.luaj.vm2.Varargs;
* <li>atan2</li> * <li>atan2</li>
* </ul> * </ul>
* <p> * <p>
* The implementations of {@code exp()} and {@code pow()} are constructed by * The implementations of {@code exp()} and {@code pow()} are constructed by
* hand for JME, so will be slower and less accurate than when executed on the JSE platform. * hand for JME, so will be slower and less accurate than when executed on the JSE platform.
* <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> {@code * <pre> {@code
* Globals globals = JsePlatform.standardGlobals(); * Globals globals = JsePlatform.standardGlobals();
* 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, * When using {@link org.luaj.vm2.lib.jse.JsePlatform} as in this example,
* the subclass {@link org.luaj.vm2.lib.jse.JseMathLib} will * the subclass {@link org.luaj.vm2.lib.jse.JseMathLib} will
* be included, which also includes this base functionality. * be included, which also includes this base functionality.
* <p> * <p>
* To instantiate and use it directly, * To instantiate and use it directly,
* link it into your globals table via {@link LuaValue#load(LuaValue)} using code such as: * link it into your globals table via {@link LuaValue#load(LuaValue)} using code such as:
* <pre> {@code * <pre> {@code
* Globals globals = new Globals(); * Globals globals = new Globals();
@@ -70,8 +70,8 @@ import org.luaj.vm2.Varargs;
* globals.load(new MathLib()); * globals.load(new MathLib());
* 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 * Doing so will ensure the library is properly initialized
* and loaded into the globals table. * and loaded into the globals table.
* <p> * <p>
* This has been implemented to match as closely as possible the behavior in the corresponding library in C. * This has been implemented to match as closely as possible the behavior in the corresponding library in C.
* @see LibFunction * @see LibFunction
@@ -87,8 +87,8 @@ public class MathLib extends TwoArgFunction {
*/ */
public static MathLib MATHLIB = null; public static MathLib MATHLIB = null;
/** Construct a MathLib, which can be initialized by calling it with a /** Construct a MathLib, which can be initialized by calling it with a
* modname string, and a global environment table as arguments using * modname string, and a global environment table as arguments using
* {@link #call(LuaValue, LuaValue)}. */ * {@link #call(LuaValue, LuaValue)}. */
public MathLib() { public MathLib() {
MATHLIB = this; MATHLIB = this;
@@ -125,7 +125,7 @@ public class MathLib extends TwoArgFunction {
math.set("sqrt", new sqrt()); math.set("sqrt", new sqrt());
math.set("tan", new tan()); math.set("tan", new tan());
env.set("math", math); env.set("math", math);
env.get("package").get("loaded").set("math", math); if (!env.get("package").isnil()) env.get("package").get("loaded").set("math", math);
return math; return math;
} }
@@ -158,9 +158,9 @@ public class MathLib extends TwoArgFunction {
exp(MathLib mathlib) { exp(MathLib mathlib) {
this.mathlib = mathlib; this.mathlib = mathlib;
} }
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 {
@@ -263,26 +263,26 @@ public class MathLib extends TwoArgFunction {
/** compute power using installed math library, or default if there is no math library installed */ /** compute power using installed math library, or default if there is no math library installed */
public static LuaValue dpow(double a, double b) { public static LuaValue dpow(double a, double b) {
return LuaDouble.valueOf( return LuaDouble.valueOf(
MATHLIB!=null? MATHLIB!=null?
MATHLIB.dpow_lib(a,b): MATHLIB.dpow_lib(a,b):
dpow_default(a,b) ); dpow_default(a,b) );
} }
public static double dpow_d(double a, double b) { public static double dpow_d(double a, double b) {
return MATHLIB!=null? return MATHLIB!=null?
MATHLIB.dpow_lib(a,b): MATHLIB.dpow_lib(a,b):
dpow_default(a,b); dpow_default(a,b);
} }
/** /**
* Hook to override default dpow behavior with faster implementation. * Hook to override default dpow behavior with faster implementation.
*/ */
public double dpow_lib(double a, double b) { public double dpow_lib(double a, double b) {
return dpow_default(a,b); return dpow_default(a,b);
} }
/** /**
* Default JME version computes using longhand heuristics. * Default JME version computes using longhand heuristics.
*/ */
protected static double dpow_default(double a, double b) { protected static double dpow_default(double a, double b) {
if ( b < 0 ) if ( b < 0 )

View File

@@ -35,17 +35,17 @@ import org.luaj.vm2.Varargs;
* Subclass of {@link LibFunction} which implements the standard lua {@code os} library. * Subclass of {@link LibFunction} which implements the standard lua {@code os} library.
* <p> * <p>
* It is a usable base with simplified stub functions * It is a usable base with simplified stub functions
* for library functions that cannot be implemented uniformly * for library functions that cannot be implemented uniformly
* on Jse and Jme. * on Jse and Jme.
* <p> * <p>
* This can be installed as-is on either platform, or extended * This can be installed as-is on either platform, or extended
* and refined to be used in a complete Jse implementation. * and refined to be used in a complete Jse implementation.
* <p> * <p>
* Because the nature of the {@code os} library is to encapsulate * Because the nature of the {@code os} library is to encapsulate
* os-specific features, the behavior of these functions varies considerably * os-specific features, the behavior of these functions varies considerably
* from their counterparts in the C platform. * from their counterparts in the C platform.
* <p> * <p>
* The following functions have limited implementations of features * The following functions have limited implementations of features
* that are not supported well on Jme: * that are not supported well on Jme:
* <ul> * <ul>
* <li>{@code execute()}</li> * <li>{@code execute()}</li>
@@ -54,7 +54,7 @@ import org.luaj.vm2.Varargs;
* <li>{@code tmpname()}</li> * <li>{@code tmpname()}</li>
* </ul> * </ul>
* <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.jme.JmePlatform#standardGlobals()} * {@link org.luaj.vm2.lib.jse.JsePlatform#standardGlobals()} or {@link org.luaj.vm2.lib.jme.JmePlatform#standardGlobals()}
* <pre> {@code * <pre> {@code
* Globals globals = JsePlatform.standardGlobals(); * Globals globals = JsePlatform.standardGlobals();
@@ -63,7 +63,7 @@ import org.luaj.vm2.Varargs;
* In this example the platform-specific {@link org.luaj.vm2.lib.jse.JseOsLib} library will be loaded, which will include * In this example the platform-specific {@link org.luaj.vm2.lib.jse.JseOsLib} library will be loaded, which will include
* the base functionality provided by this class. * the base functionality provided by this class.
* <p> * <p>
* To instantiate and use it directly, * To instantiate and use it directly,
* link it into your globals table via {@link LuaValue#load(LuaValue)} using code such as: * link it into your globals table via {@link LuaValue#load(LuaValue)} using code such as:
* <pre> {@code * <pre> {@code
* Globals globals = new Globals(); * Globals globals = new Globals();
@@ -114,8 +114,8 @@ public class OsLib extends TwoArgFunction {
protected Globals globals; protected Globals globals;
/** /**
* Create and OsLib instance. * Create and OsLib instance.
*/ */
public OsLib() { public OsLib() {
} }
@@ -132,7 +132,7 @@ public class OsLib extends TwoArgFunction {
for (int i = 0; i < NAMES.length; ++i) for (int i = 0; i < NAMES.length; ++i)
os.set(NAMES[i], new OsLibFunc(i, NAMES[i])); os.set(NAMES[i], new OsLibFunc(i, NAMES[i]));
env.set("os", os); env.set("os", os);
env.get("package").get("loaded").set("os", os); if (!env.get("package").isnil()) env.get("package").get("loaded").set("os", os);
return os; return os;
} }
@@ -200,8 +200,8 @@ public class OsLib extends TwoArgFunction {
} }
/** /**
* @return an approximation of the amount in seconds of CPU time used by * @return an approximation of the amount in seconds of CPU time used by
* the program. For luaj this simple returns the elapsed time since the * the program. For luaj this simple returns the elapsed time since the
* OsLib class was loaded. * OsLib class was loaded.
*/ */
protected double clock() { protected double clock() {
@@ -209,7 +209,7 @@ public class OsLib extends TwoArgFunction {
} }
/** /**
* Returns the number of seconds from time t1 to time t2. * Returns the number of seconds from time t1 to time t2.
* In POSIX, Windows, and some other systems, this value is exactly t2-t1. * In POSIX, Windows, and some other systems, this value is exactly t2-t1.
* @param t2 * @param t2
* @param t1 * @param t1
@@ -220,21 +220,21 @@ public class OsLib extends TwoArgFunction {
} }
/** /**
* If the time argument is present, this is the time to be formatted * If the time argument is present, this is the time to be formatted
* (see the os.time function for a description of this value). * (see the os.time function for a description of this value).
* Otherwise, date formats the current time. * Otherwise, date formats the current time.
* *
* Date returns the date as a string, * Date returns the date as a string,
* formatted according to the same rules as ANSII strftime, but without * formatted according to the same rules as ANSII strftime, but without
* support for %g, %G, or %V. * support for %g, %G, or %V.
* *
* When called without arguments, date returns a reasonable date and * When called without arguments, date returns a reasonable date and
* time representation that depends on the host system and on the * time representation that depends on the host system and on the
* current locale (that is, os.date() is equivalent to os.date("%c")). * current locale (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, * @return a LString or a LTable containing date and time,
* formatted according to the given string format. * formatted according to the given string format.
*/ */
public String date(String format, double time) { public String date(String format, double time) {
@@ -277,8 +277,8 @@ public class OsLib extends TwoArgFunction {
break; break;
case 'B': case 'B':
result.append(MonthName[d.get(Calendar.MONTH)]); result.append(MonthName[d.get(Calendar.MONTH)]);
break; break;
case 'c': case 'c':
result.append(date("%a %b %d %H:%M:%S %Y", time)); result.append(date("%a %b %d %H:%M:%S %Y", time));
break; break;
case 'd': case 'd':
@@ -314,7 +314,7 @@ public class OsLib extends TwoArgFunction {
case 'w': case 'w':
result.append(String.valueOf((d.get(Calendar.DAY_OF_WEEK)+6)%7)); result.append(String.valueOf((d.get(Calendar.DAY_OF_WEEK)+6)%7));
break; break;
case 'W': case 'W':
result.append(String.valueOf(weekNumber(d, 1))); result.append(String.valueOf(weekNumber(d, 1)));
break; break;
case 'x': case 'x':
@@ -372,7 +372,7 @@ public class OsLib extends TwoArgFunction {
} }
private int timeZoneOffset(Calendar d) { private int timeZoneOffset(Calendar d) {
int localStandarTimeMillis = ( int localStandarTimeMillis = (
d.get(Calendar.HOUR_OF_DAY) * 3600 + d.get(Calendar.HOUR_OF_DAY) * 3600 +
d.get(Calendar.MINUTE) * 60 + d.get(Calendar.MINUTE) * 60 +
d.get(Calendar.SECOND)) * 1000; d.get(Calendar.SECOND)) * 1000;
@@ -381,28 +381,28 @@ public class OsLib extends TwoArgFunction {
d.get(Calendar.YEAR), d.get(Calendar.YEAR),
d.get(Calendar.MONTH), d.get(Calendar.MONTH),
d.get(Calendar.DAY_OF_MONTH), d.get(Calendar.DAY_OF_MONTH),
d.get(Calendar.DAY_OF_WEEK), d.get(Calendar.DAY_OF_WEEK),
localStandarTimeMillis) / 1000; localStandarTimeMillis) / 1000;
} }
private boolean isDaylightSavingsTime(Calendar d) { private boolean isDaylightSavingsTime(Calendar d) {
return timeZoneOffset(d) != d.getTimeZone().getRawOffset() / 1000; return timeZoneOffset(d) != d.getTimeZone().getRawOffset() / 1000;
} }
/** /**
* This function is equivalent to the C function system. * This function is equivalent to the C function system.
* It passes command to be executed by an operating system shell. * It passes command to be executed by an operating system shell.
* It returns a status code, which is system-dependent. * It returns a status code, which is system-dependent.
* If command is absent, then it returns nonzero if a shell * If command is absent, then it returns nonzero if a shell
* is available and zero otherwise. * 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) {
return varargsOf(NIL, valueOf("exit"), ONE); return varargsOf(NIL, valueOf("exit"), ONE);
} }
/** /**
* Calls the C function exit, with an optional code, to terminate the host program. * Calls the C function exit, with an optional code, to terminate the host program.
* @param code * @param code
*/ */
protected void exit(int code) { protected void exit(int code) {
@@ -415,13 +415,13 @@ public class OsLib extends TwoArgFunction {
* or null if the variable is not defined in either environment. * or null if the variable is not defined in either environment.
* *
* The default implementation, which is used by the JmePlatform, * The default implementation, which is used by the JmePlatform,
* only queryies System.getProperty(). * only queryies System.getProperty().
* *
* The JsePlatform overrides this behavior and returns the * The JsePlatform overrides this behavior and returns the
* environment variable value using System.getenv() if it exists, * environment variable value using System.getenv() if it exists,
* or the System property value if it does not. * or the System property value if it does not.
* *
* A SecurityException may be thrown if access is not allowed * A SecurityException may be thrown if access is not allowed
* for 'varname'. * for 'varname'.
* @param varname * @param varname
* @return String value, or null if not defined * @return String value, or null if not defined
@@ -431,10 +431,10 @@ public class OsLib extends TwoArgFunction {
} }
/** /**
* Deletes the file or directory with the given name. * Deletes the file or directory with the given name.
* Directories must be empty to be removed. * Directories must be empty to be removed.
* If this function fails, it throws and IOException * If this function fails, it throws and IOException
* *
* @param filename * @param filename
* @throws IOException if it fails * @throws IOException if it fails
*/ */
@@ -443,9 +443,9 @@ public class OsLib extends TwoArgFunction {
} }
/** /**
* Renames file or directory named oldname to newname. * Renames file or directory named oldname to newname.
* If this function fails,it throws and IOException * If this function 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
@@ -455,21 +455,21 @@ public class OsLib extends TwoArgFunction {
} }
/** /**
* Sets the current locale of the program. locale is a string specifying * Sets the current locale of the program. locale is a string specifying
* a locale; category is an optional string describing which category to change: * a locale; category is an optional string describing which category to change:
* "all", "collate", "ctype", "monetary", "numeric", or "time"; the default category * "all", "collate", "ctype", "monetary", "numeric", or "time"; the default category
* is "all". * is "all".
* *
* If locale is the empty string, the current locale is set to an implementation- * If locale is the empty string, the current locale is set to an implementation-
* defined native locale. If locale is the string "C", the current locale is set * defined native locale. If locale is the string "C", the current locale is set
* to the standard C locale. * to the standard C locale.
* *
* When called with null as the first argument, this function only returns the * When called with null as the first argument, this function only returns the
* name of the current locale for the given category. * 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 * @return the name of the new locale, or null if the request
* cannot be honored. * cannot be honored.
*/ */
protected String setlocale(String locale, String category) { protected String setlocale(String locale, String category) {
@@ -477,10 +477,10 @@ public class OsLib extends TwoArgFunction {
} }
/** /**
* Returns the current time when called without arguments, * Returns the current time when called without arguments,
* or a time representing the date and time specified by the given table. * or a time representing the date and time specified by the given table.
* This table must have fields year, month, and day, * This table must have fields year, month, and day,
* and may have fields hour, min, sec, and isdst * and may have fields hour, min, sec, and isdst
* (for a description of these fields, see the os.date function). * (for a description of these fields, see the os.date function).
* @param table * @param table
* @return long value for the time * @return long value for the time
@@ -504,15 +504,15 @@ 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 name, * On some systems (POSIX), this function also creates a file with that name,
* to avoid security risks. (Someone else might create the file with wrong * to avoid security risks. (Someone else might create the file with wrong
* permissions in the time between getting the name and creating the file.) * permissions in the time between getting the name and creating the file.)
* You still have to open the file to use it and to remove it (even if you * You still have to open the file to use it and to remove it (even if you
* do not use it). * do not use it).
* *
* @return String filename to use * @return String filename to use
*/ */

View File

@@ -24,26 +24,26 @@ package org.luaj.vm2.lib;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.IOException; import java.io.IOException;
import org.luaj.vm2.LuaClosure;
import org.luaj.vm2.Buffer; import org.luaj.vm2.Buffer;
import org.luaj.vm2.LuaClosure;
import org.luaj.vm2.LuaString; import org.luaj.vm2.LuaString;
import org.luaj.vm2.LuaTable; import org.luaj.vm2.LuaTable;
import org.luaj.vm2.LuaValue; import org.luaj.vm2.LuaValue;
import org.luaj.vm2.Varargs; import org.luaj.vm2.Varargs;
import org.luaj.vm2.compiler.DumpState; import org.luaj.vm2.compiler.DumpState;
/** /**
* Subclass of {@link LibFunction} which implements the lua standard {@code string} * Subclass of {@link LibFunction} which implements the lua standard {@code string}
* library. * 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.jme.JmePlatform#standardGlobals()} * {@link org.luaj.vm2.lib.jse.JsePlatform#standardGlobals()} or {@link org.luaj.vm2.lib.jme.JmePlatform#standardGlobals()}
* <pre> {@code * <pre> {@code
* Globals globals = JsePlatform.standardGlobals(); * Globals globals = JsePlatform.standardGlobals();
* System.out.println( globals.get("string").get("upper").call( LuaValue.valueOf("abcde") ) ); * System.out.println( globals.get("string").get("upper").call( LuaValue.valueOf("abcde") ) );
* } </pre> * } </pre>
* <p> * <p>
* To instantiate and use it directly, * To instantiate and use it directly,
* link it into your globals table via {@link LuaValue#load(LuaValue)} using code such as: * link it into your globals table via {@link LuaValue#load(LuaValue)} using code such as:
* <pre> {@code * <pre> {@code
* Globals globals = new Globals(); * Globals globals = new Globals();
@@ -61,8 +61,8 @@ import org.luaj.vm2.compiler.DumpState;
*/ */
public class StringLib extends TwoArgFunction { public class StringLib extends TwoArgFunction {
/** Construct a StringLib, which can be initialized by calling it with a /** Construct a StringLib, which can be initialized by calling it with a
* modname string, and a global environment table as arguments using * modname string, and a global environment table as arguments using
* {@link #call(LuaValue, LuaValue)}. */ * {@link #call(LuaValue, LuaValue)}. */
public StringLib() { public StringLib() {
} }
@@ -75,8 +75,8 @@ public class StringLib extends TwoArgFunction {
* If the shared strings metatable instance is null, will set the metatable as * If the shared strings metatable instance is null, will set the metatable as
* the global shared metatable for strings. * the global shared metatable for strings.
* <P> * <P>
* All tables and metatables are read-write by default so if this will be used in * All tables and metatables are read-write by default so if this will be used in
* a server environment, sandboxing should be used. In particular, the * a server environment, sandboxing should be used. In particular, the
* {@link LuaString#s_metatable} table should probably be made read-only. * {@link LuaString#s_metatable} table should probably be made 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 instance. * @param env the environment to load into, typically a Globals instance.
@@ -99,7 +99,7 @@ public class StringLib extends TwoArgFunction {
string.set("upper", new upper()); string.set("upper", new upper());
env.set("string", string); env.set("string", string);
env.get("package").get("loaded").set("string", string); if (!env.get("package").isnil()) env.get("package").get("loaded").set("string", string);
if (LuaString.s_metatable == null) { if (LuaString.s_metatable == null) {
LuaString.s_metatable = LuaValue.tableOf(new LuaValue[] { INDEX, string }); LuaString.s_metatable = LuaValue.tableOf(new LuaValue[] { INDEX, string });
} }
@@ -107,7 +107,7 @@ public class StringLib extends TwoArgFunction {
} }
/** /**
* string.byte (s [, i [, j]]) * string.byte (s [, i [, j]])
* *
* Returns the internal numerical codes of the * Returns the internal numerical codes of the
* characters s[i], s[i+1], ..., s[j]. The default value for i is 1; the * characters s[i], s[i+1], ..., s[j]. The default value for i is 1; the
@@ -137,12 +137,12 @@ public class StringLib extends TwoArgFunction {
} }
} }
/** /**
* string.char (...) * string.char (...)
* *
* Receives zero or more integers. Returns a string with length equal * Receives zero or more integers. Returns a string with length equal
* to the number of arguments, in which each character has the internal * to the number of arguments, in which each character has the internal
* numerical code equal to its corresponding argument. * numerical 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.
* *
@@ -161,15 +161,15 @@ public class StringLib extends TwoArgFunction {
} }
} }
/** /**
* string.dump (function[, stripDebug]) * string.dump (function[, stripDebug])
* *
* Returns a string containing a binary representation of the given function, * 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. * function must be a Lua function without upvalues.
* Boolean param stripDebug - true to strip debugging info, false otherwise. * Boolean param stripDebug - true to strip debugging info, false otherwise.
* The default value for stripDebug is true. * The default 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 {
@@ -185,20 +185,20 @@ 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. * Looks for the first match of pattern in the string s.
* If it finds a match, then find returns the indices of s * If it finds a match, then find returns the indices of s
* where this occurrence starts and ends; otherwise, it returns nil. * where this occurrence starts and ends; otherwise, it returns nil.
* A third, optional numerical argument init specifies where to start the search; * A third, optional numerical argument init specifies where to start the search;
* its default value is 1 and may be negative. A value of true as a fourth, * its default value is 1 and may be negative. A value of true as a fourth,
* optional argument plain turns off the pattern matching facilities, * optional argument plain turns off the pattern matching facilities,
* so the function does a plain "find substring" operation, * so the function does a plain "find substring" operation,
* with no characters in pattern being considered "magic". * with no characters in pattern being considered "magic".
* Note that if plain is given, then init must be given as well. * Note that if plain is given, then init must be given as well.
* *
* If the pattern has captures, then in a successful match the captured values * If the pattern has captures, then in a successful match the captured values
* are also returned, after the two indices. * are also returned, after the two indices.
*/ */
static final class find extends VarArgFunction { static final class find extends VarArgFunction {
@@ -207,28 +207,28 @@ 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 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 functions. * The format string follows the same rules as the printf family of standard C functions.
* The only differences are that the options/modifiers *, l, L, n, p, and h are not supported * The only differences are that the options/modifiers *, l, L, n, p, and h are not supported
* and that there is an extra option, q. The q option formats a string in a form suitable * and that there is an extra option, q. The q option formats a string in a form suitable
* to be safely read back by the Lua interpreter: the string is written between double quotes, * to be safely read back by the Lua interpreter: the string is written between double quotes,
* and all double quotes, newlines, embedded zeros, and backslashes in the string are correctly * and all double quotes, newlines, embedded zeros, and backslashes in the string are correctly
* escaped when written. For instance, the call * escaped when written. For instance, the call
* 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: * will produce the string:
* "a string with \"quotes\" and \ * "a string with \"quotes\" and \
* new line" * new line"
*
* The options c, d, E, e, f, g, G, i, o, u, X, and x all expect a number as argument,
* whereas q and s expect a string.
* *
* This function does not accept string values containing embedded zeros, * The options c, d, E, e, f, g, G, i, o, u, X, and x all expect a number as argument,
* except as arguments to the q option. * whereas q and s expect a string.
*
* This function does not accept string values containing embedded zeros,
* except as arguments to the q option.
*/ */
static final class format extends VarArgFunction { static final class format extends VarArgFunction {
public Varargs invoke(Varargs args) { public Varargs invoke(Varargs args) {
@@ -493,20 +493,20 @@ 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 next captures * Returns an iterator function that, each time it is called, returns the next captures
* from pattern over string s. If pattern specifies no captures, then the * from pattern over string s. If pattern specifies no captures, then the
* whole match is produced in each call. * whole match is produced in each call.
* *
* As an example, the following loop * As an example, the following loop
* s = "hello world from Lua" * s = "hello world from Lua"
* for w in string.gmatch(s, "%a+") do * for w in string.gmatch(s, "%a+") do
* print(w) * print(w)
* end * end
* *
* will iterate over all the words from string s, printing one per line. * will iterate over all the words from string s, printing one per line.
* The next example collects all pairs key=value from the given string into a table: * The next example collects all pairs key=value from the given string into a table:
* t = {} * t = {}
* s = "from=world, to=Lua" * s = "from=world, to=Lua"
@@ -514,7 +514,7 @@ public class StringLib extends TwoArgFunction {
* t[k] = v * t[k] = v
* end * end
* *
* For this function, a '^' at the start of a pattern does not work as an anchor, * For this function, a '^' at the start of a pattern does not work as an anchor,
* as this would prevent the iteration. * as this would prevent the iteration.
*/ */
static final class gmatch extends VarArgFunction { static final class gmatch extends VarArgFunction {
@@ -550,28 +550,28 @@ public class StringLib extends TwoArgFunction {
} }
/** /**
* string.gsub (s, pattern, repl [, n]) * string.gsub (s, pattern, repl [, n])
* Returns a copy of s in which all (or the first n, if given) occurrences of the * Returns a copy of s in which all (or the first n, if given) occurrences of the
* pattern have been replaced by a replacement string specified by repl, which * pattern have been replaced by a replacement string specified by repl, which
* may be a string, a table, or a function. gsub also returns, as its second value, * may be a string, a table, or a function. gsub also returns, as its second value,
* the total number of matches that occurred. * the total number of matches that occurred.
* *
* If repl is a string, then its value is used for replacement. * If repl is a string, then its value is used for replacement.
* The character % works as an escape character: any sequence in repl of the form %n, * The character % works as an escape character: any sequence in repl of the form %n,
* with n between 1 and 9, stands for the value of the n-th captured substring (see below). * with n between 1 and 9, stands for the value of the n-th captured substring (see below).
* The sequence %0 stands for the whole match. The sequence %% stands for a single %. * The sequence %0 stands for the whole match. The sequence %% stands for a single %.
*
* If repl is a table, then the table is queried for every match, using the first capture
* as the key; if the pattern specifies no captures, then the whole match is used as the key.
* *
* If repl is a function, then this function is called every time a match occurs, * If repl is a table, then the table is queried for every match, using the first capture
* with all captured substrings passed as arguments, in order; if the pattern specifies * as the key; if the pattern specifies no captures, then the whole match is used as the key.
* no captures, then the whole match is passed as a sole argument.
* *
* If the value returned by the table query or by the function call is a string or a number, * If repl is a function, then this function is called every time a match occurs,
* then it is used as the replacement string; otherwise, if it is false or nil, * with all captured substrings passed as arguments, in order; if the pattern specifies
* then there is no replacement (that is, the original match is kept in the string). * no captures, then the whole match is passed as a sole argument.
*
* If the value returned by the table query or by the function call is a string or a number,
* then it is used as the replacement string; otherwise, if it is false or nil,
* then there is no replacement (that is, the original match is kept in the string).
* *
* Here are some examples: * Here are some examples:
* x = string.gsub("hello world", "(%w+)", "%1 %1") * x = string.gsub("hello world", "(%w+)", "%1 %1")
@@ -630,11 +630,11 @@ public class StringLib extends TwoArgFunction {
} }
} }
/** /**
* string.len (s) * string.len (s)
* *
* Receives a string and returns its length. The empty string "" has length 0. * Receives a string and returns its length. The empty string "" has length 0.
* Embedded zeros are counted, so "a\000bc\000" has length 5. * Embedded zeros are counted, so "a\000bc\000" has length 5.
*/ */
static final class len extends OneArgFunction { static final class len extends OneArgFunction {
public LuaValue call(LuaValue arg) { public LuaValue call(LuaValue arg) {
@@ -642,11 +642,11 @@ public class StringLib extends TwoArgFunction {
} }
} }
/** /**
* string.lower (s) * string.lower (s)
* *
* Receives a string and returns a copy of this string with all uppercase letters * Receives a string and returns a copy of this string with all uppercase letters
* changed to lowercase. All other characters are left unchanged. * changed to lowercase. All other characters are left unchanged.
* The definition of what an uppercase letter is depends on the current locale. * The definition of what an uppercase letter is depends on the current locale.
*/ */
static final class lower extends OneArgFunction { static final class lower extends OneArgFunction {
@@ -673,7 +673,7 @@ 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 {
public Varargs invoke(Varargs args) { public Varargs invoke(Varargs args) {
@@ -688,10 +688,10 @@ 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 {
public LuaValue call(LuaValue arg) { public LuaValue call(LuaValue arg) {
@@ -704,15 +704,15 @@ 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; * 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 * i and j may be negative. If j is absent, then it is assumed to be equal to -1
* (which is the same as the string length). In particular, the call * (which is the same as the string length). In particular, the call
* string.sub(s,1,j) * string.sub(s,1,j)
* returns a prefix of s with length j, and * returns a prefix of s with length j, and
* string.sub(s, -i) * string.sub(s, -i)
* returns a suffix of s with length i. * returns a suffix of s with length i.
*/ */
static final class sub extends VarArgFunction { static final class sub extends VarArgFunction {
@@ -736,12 +736,12 @@ public class StringLib extends TwoArgFunction {
} }
} }
/** /**
* string.upper (s) * string.upper (s)
* *
* Receives a string and returns a copy of this string with all lowercase letters * Receives a string and returns a copy of this string with all lowercase letters
* changed to uppercase. All other characters are left unchanged. * changed to uppercase. All other characters are left unchanged.
* The definition of what a lowercase letter is depends on the current locale. * The definition of what a lowercase letter is depends on the current locale.
*/ */
static final class upper extends OneArgFunction { static final class upper extends OneArgFunction {
public LuaValue call(LuaValue arg) { public LuaValue call(LuaValue arg) {
@@ -1055,7 +1055,7 @@ public class StringLib extends TwoArgFunction {
*/ */
int match( int soffset, int poffset ) { int match( int soffset, int poffset ) {
while ( true ) { while ( true ) {
// Check if we are at the end of the pattern - // Check if we are at the end of the pattern -
// equivalent to the '\0' case in the C version, but our pattern // equivalent to the '\0' case in the C version, but our pattern
// string is not NUL-terminated. // string is not NUL-terminated.
if ( poffset == p.length() ) if ( poffset == p.length() )

View File

@@ -25,19 +25,19 @@ import org.luaj.vm2.LuaTable;
import org.luaj.vm2.LuaValue; import org.luaj.vm2.LuaValue;
import org.luaj.vm2.Varargs; import org.luaj.vm2.Varargs;
/** /**
* Subclass of {@link LibFunction} which implements the lua standard {@code table} * Subclass of {@link LibFunction} which implements the lua standard {@code table}
* library. * 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.jme.JmePlatform#standardGlobals()} * {@link org.luaj.vm2.lib.jse.JsePlatform#standardGlobals()} or {@link org.luaj.vm2.lib.jme.JmePlatform#standardGlobals()}
* <pre> {@code * <pre> {@code
* Globals globals = JsePlatform.standardGlobals(); * Globals globals = JsePlatform.standardGlobals();
* System.out.println( globals.get("table").get("length").call( LuaValue.tableOf() ) ); * System.out.println( globals.get("table").get("length").call( LuaValue.tableOf() ) );
* } </pre> * } </pre>
* <p> * <p>
* To instantiate and use it directly, * To instantiate and use it directly,
* link it into your globals table via {@link LuaValue#load(LuaValue)} using code such as: * link it into your globals table via {@link LuaValue#load(LuaValue)} using code such as:
* <pre> {@code * <pre> {@code
* Globals globals = new Globals(); * Globals globals = new Globals();
@@ -70,7 +70,7 @@ public class TableLib extends TwoArgFunction {
table.set("sort", new sort()); table.set("sort", new sort());
table.set("unpack", new unpack()); table.set("unpack", new unpack());
env.set("table", table); env.set("table", table);
env.get("package").get("loaded").set("table", table); if (!env.get("package").isnil()) env.get("package").get("loaded").set("table", table);
return NIL; return NIL;
} }

View File

@@ -37,38 +37,38 @@ import org.luaj.vm2.compiler.LuaC;
import org.luaj.vm2.lib.LibFunction; import org.luaj.vm2.lib.LibFunction;
import org.luaj.vm2.lib.VarArgFunction; import org.luaj.vm2.lib.VarArgFunction;
/** /**
* Subclass of {@link LibFunction} which implements the features of the luajava package. * Subclass of {@link LibFunction} which implements the features of the luajava package.
* <p> * <p>
* Luajava is an approach to mixing lua and java using simple functions that bind * Luajava is an approach to mixing lua and java using simple functions that bind
* java classes and methods to lua dynamically. The API is documented on the * java classes and methods to lua dynamically. The API is documented on the
* <a href="http://www.keplerproject.org/luajava/">luajava</a> documentation pages. * <a href="http://www.keplerproject.org/luajava/">luajava</a> documentation 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> {@code * <pre> {@code
* Globals globals = JsePlatform.standardGlobals(); * Globals globals = JsePlatform.standardGlobals();
* System.out.println( globals.get("luajava").get("bindClass").call( LuaValue.valueOf("java.lang.System") ).invokeMethod("currentTimeMillis") ); * System.out.println( globals.get("luajava").get("bindClass").call( LuaValue.valueOf("java.lang.System") ).invokeMethod("currentTimeMillis") );
* } </pre> * } </pre>
* <p> * <p>
* To instantiate and use it directly, * To instantiate and use it directly,
* link it into your globals table via {@link Globals#load} using code such as: * link it into your globals table via {@link Globals#load} using code such as:
* <pre> {@code * <pre> {@code
* Globals globals = new Globals(); * Globals globals = new Globals();
* globals.load(new JseBaseLib()); * globals.load(new JseBaseLib());
* globals.load(new PackageLib()); * globals.load(new PackageLib());
* globals.load(new LuajavaLib()); * globals.load(new LuajavaLib());
* globals.load( * globals.load(
* "sys = luajava.bindClass('java.lang.System')\n"+ * "sys = luajava.bindClass('java.lang.System')\n"+
* "print ( sys:currentTimeMillis() )\n", "main.lua" ).call(); * "print ( sys:currentTimeMillis() )\n", "main.lua" ).call();
* } </pre> * } </pre>
* <p> * <p>
* *
* The {@code luajava} library is available * The {@code luajava} library is available
* on all JSE platforms via the call to {@link org.luaj.vm2.lib.jse.JsePlatform#standardGlobals()} * on all JSE platforms via the call to {@link org.luaj.vm2.lib.jse.JsePlatform#standardGlobals()}
* and the luajava api's are simply invoked from lua. * and the luajava api's are simply invoked from lua.
* Because it makes extensive use of Java's reflection API, it is not available * Because it makes extensive use of Java's reflection API, it is not available
* on JME, but can be used in Android applications. * on JME, but can be used in Android applications.
* <p> * <p>
* This has been implemented to match as closely as possible the behavior in the corresponding library in C. * This has been implemented to match as closely as possible the behavior in the corresponding library in C.
@@ -91,10 +91,10 @@ public class LuajavaLib extends VarArgFunction {
static final int LOADLIB = 5; static final int LOADLIB = 5;
static final String[] NAMES = { static final String[] NAMES = {
"bindClass", "bindClass",
"newInstance", "newInstance",
"new", "new",
"createProxy", "createProxy",
"loadLib", "loadLib",
}; };
@@ -112,7 +112,7 @@ public class LuajavaLib extends VarArgFunction {
LuaTable t = new LuaTable(); LuaTable t = new LuaTable();
bind( t, this.getClass(), NAMES, BINDCLASS ); bind( t, this.getClass(), NAMES, BINDCLASS );
env.set("luajava", t); env.set("luajava", t);
env.get("package").get("loaded").set("luajava", t); if (!env.get("package").isnil()) env.get("package").get("loaded").set("luajava", t);
return t; return t;
} }
case BINDCLASS: { case BINDCLASS: {
@@ -122,13 +122,13 @@ public class LuajavaLib extends VarArgFunction {
case NEWINSTANCE: case NEWINSTANCE:
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()): (Class) c.checkuserdata(Class.class)); final Class clazz = (opcode==NEWINSTANCE? classForName(c.tojstring()): (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);
} }
case CREATEPROXY: { case CREATEPROXY: {
final int niface = args.narg()-1; final int niface = args.narg()-1;
if ( niface <= 0 ) if ( niface <= 0 )
throw new LuaError("no interfaces"); throw new LuaError("no interfaces");
@@ -136,7 +136,7 @@ public class LuajavaLib extends VarArgFunction {
// get the interfaces // get the interfaces
final Class[] ifaces = new Class[niface]; final Class[] ifaces = new Class[niface];
for ( int i=0; i<niface; i++ ) for ( int i=0; i<niface; i++ )
ifaces[i] = classForName(args.checkjstring(i+1)); ifaces[i] = classForName(args.checkjstring(i+1));
// create the invocation handler // create the invocation handler
@@ -191,16 +191,16 @@ public class LuajavaLib extends VarArgFunction {
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 ) {
Object o = args[--n]; Object o = args[--n];
int m = Array.getLength( o ); int m = Array.getLength( o );
v = new LuaValue[n+m]; v = new LuaValue[n+m];
for ( int i=0; i<n; i++ ) for ( int i=0; i<n; i++ )
v[i] = CoerceJavaToLua.coerce(args[i]); v[i] = CoerceJavaToLua.coerce(args[i]);
for ( int i=0; i<m; i++ ) for ( int i=0; i<m; i++ )
v[i+n] = CoerceJavaToLua.coerce(Array.get(o,i)); v[i+n] = CoerceJavaToLua.coerce(Array.get(o,i));
} else { } else {
v = new LuaValue[n]; v = new LuaValue[n];
for ( int i=0; i<n; i++ ) for ( int i=0; i<n; i++ )