diff --git a/src/core/org/luaj/vm2/lib/Bit32Lib.java b/src/core/org/luaj/vm2/lib/Bit32Lib.java index 55db4f13..699c6945 100644 --- a/src/core/org/luaj/vm2/lib/Bit32Lib.java +++ b/src/core/org/luaj/vm2/lib/Bit32Lib.java @@ -27,15 +27,15 @@ import org.luaj.vm2.Varargs; /** * Subclass of LibFunction that implements the Lua standard {@code bit32} library. - *

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

 {@code
  * Globals globals = JsePlatform.standardGlobals();
  * System.out.println( globals.get("bit32").get("bnot").call( LuaValue.valueOf(2) ) );
  * } 
*

- * 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: *

 {@code
  * Globals globals = new Globals();
@@ -71,7 +71,7 @@ public class Bit32Lib extends TwoArgFunction {
 			"arshift", "lrotate", "lshift", "rrotate", "rshift"
 		});
 		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;
 	}
 
@@ -219,6 +219,6 @@ public class Bit32Lib extends TwoArgFunction {
 	}
 
 	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);
 	}
 }
diff --git a/src/core/org/luaj/vm2/lib/CoroutineLib.java b/src/core/org/luaj/vm2/lib/CoroutineLib.java
index f7c3dfae..28cb246b 100644
--- a/src/core/org/luaj/vm2/lib/CoroutineLib.java
+++ b/src/core/org/luaj/vm2/lib/CoroutineLib.java
@@ -27,25 +27,25 @@ import org.luaj.vm2.LuaThread;
 import org.luaj.vm2.LuaValue;
 import org.luaj.vm2.Varargs;
 
-/** 
- * Subclass of {@link LibFunction} which implements the lua standard {@code coroutine} 
- * library. 
- * 

+/** + * Subclass of {@link LibFunction} which implements the lua standard {@code coroutine} + * library. + *

* The coroutine library in luaj has the same behavior as the - * coroutine library in C, but is implemented using Java Threads to maintain - * the call state between invocations. Therefore it can be yielded from anywhere, + * coroutine library in C, but is implemented using Java Threads to maintain + * 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. * However, coroutines that are yielded but never resumed to complete their execution - * may not be collected by the garbage collector. - *

- * Typically, this library is included as part of a call to either + * may not be collected by the garbage collector. + *

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

 {@code
  * Globals globals = JsePlatform.standardGlobals();
  * System.out.println( globals.get("coroutine").get("running").call() );
  * } 
*

- * 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: *

 {@code
  * Globals globals = new Globals();
@@ -82,7 +82,7 @@ public class CoroutineLib extends TwoArgFunction {
 		coroutine.set("yield", new yield());
 		coroutine.set("wrap", new wrap());
 		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;
 	}
 
diff --git a/src/core/org/luaj/vm2/lib/DebugLib.java b/src/core/org/luaj/vm2/lib/DebugLib.java
index 65b8ac05..fd7c4c3c 100644
--- a/src/core/org/luaj/vm2/lib/DebugLib.java
+++ b/src/core/org/luaj/vm2/lib/DebugLib.java
@@ -38,26 +38,26 @@ import org.luaj.vm2.Print;
 import org.luaj.vm2.Prototype;
 import org.luaj.vm2.Varargs;
 
-/** 
- * Subclass of {@link LibFunction} which implements the lua standard {@code debug} 
- * library. 
- * 

+/** + * Subclass of {@link LibFunction} which implements the lua standard {@code debug} + * 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} - * instances. + * To do this, it must maintain a separate stack of calls to {@link LuaClosure} and {@link LibFunction} + * instances. * 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}, - * this cannot be done in all cases. - *

- * Typically, this library is included as part of a call to either - * {@link org.luaj.vm2.lib.jse.JsePlatform#debugGlobals()} or + * via a {@link org.luaj.vm2.Globals.Compiler} such as {@link org.luaj.vm2.luajc.LuaJC}, + * this cannot be done in all cases. + *

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

 {@code
  * Globals globals = JsePlatform.debugGlobals();
  * System.out.println( globals.get("debug").get("traceback").call() );
  * } 
*

- * 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: *

 {@code
  * Globals globals = new Globals();
@@ -84,27 +84,27 @@ public class DebugLib extends TwoArgFunction {
 		try { TRACE = (null != System.getProperty("TRACE")); } catch (Exception e) {}
 	}
 	
-	static final LuaString LUA             = valueOf("Lua");  
-	private static final LuaString QMARK           = valueOf("?");  
-	private static final LuaString CALL            = valueOf("call");  
-	private static final LuaString LINE            = valueOf("line");  
-	private static final LuaString COUNT           = valueOf("count");  
+	static final LuaString LUA             = valueOf("Lua");
+	private static final LuaString QMARK           = valueOf("?");
+	private static final LuaString CALL            = valueOf("call");
+	private static final LuaString LINE            = valueOf("line");
+	private static final LuaString COUNT           = valueOf("count");
 	private static final LuaString RETURN          = valueOf("return");
 	
-	static final LuaString FUNC            = valueOf("func");  
-	static final LuaString ISTAILCALL      = valueOf("istailcall");  
-	static final LuaString ISVARARG        = valueOf("isvararg");  
-	static final LuaString NUPS            = valueOf("nups");  
-	static final LuaString NPARAMS         = valueOf("nparams");  
-	static final LuaString NAME            = valueOf("name");  
-	static final LuaString NAMEWHAT        = valueOf("namewhat");  
-	static final LuaString WHAT            = valueOf("what");  
-	static final LuaString SOURCE          = valueOf("source");  
-	static final LuaString SHORT_SRC       = valueOf("short_src");  
-	static final LuaString LINEDEFINED     = valueOf("linedefined");  
-	static final LuaString LASTLINEDEFINED = valueOf("lastlinedefined");  
-	static final LuaString CURRENTLINE     = valueOf("currentline");  
-	static final LuaString ACTIVELINES     = valueOf("activelines");  
+	static final LuaString FUNC            = valueOf("func");
+	static final LuaString ISTAILCALL      = valueOf("istailcall");
+	static final LuaString ISVARARG        = valueOf("isvararg");
+	static final LuaString NUPS            = valueOf("nups");
+	static final LuaString NPARAMS         = valueOf("nparams");
+	static final LuaString NAME            = valueOf("name");
+	static final LuaString NAMEWHAT        = valueOf("namewhat");
+	static final LuaString WHAT            = valueOf("what");
+	static final LuaString SOURCE          = valueOf("source");
+	static final LuaString SHORT_SRC       = valueOf("short_src");
+	static final LuaString LINEDEFINED     = valueOf("linedefined");
+	static final LuaString LASTLINEDEFINED = valueOf("lastlinedefined");
+	static final LuaString CURRENTLINE     = valueOf("currentline");
+	static final LuaString ACTIVELINES     = valueOf("activelines");
 
 	Globals globals;
 	
@@ -135,19 +135,19 @@ public class DebugLib extends TwoArgFunction {
 		debug.set("upvalueid", new upvalueid());
 		debug.set("upvaluejoin", new upvaluejoin());
 		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;
 	}
 
 	// debug.debug()
-	static final class debug extends ZeroArgFunction { 
+	static final class debug extends ZeroArgFunction {
 		public LuaValue call() {
 			return NONE;
 		}
 	}
 
 	// debug.gethook ([thread])
-	final class gethook extends VarArgFunction { 
+	final class gethook extends VarArgFunction {
 		public Varargs invoke(Varargs args) {
 			LuaThread t = args.narg() > 0 ? args.checkthread(1): globals.running;
 			LuaThread.State s = t.state;
@@ -159,10 +159,10 @@ public class DebugLib extends TwoArgFunction {
 	}
 
 	//	debug.getinfo ([thread,] f [, what])
-	final class getinfo extends VarArgFunction { 
+	final class getinfo extends VarArgFunction {
 		public Varargs invoke(Varargs args) {
 			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++);
 			String what = args.optjstring(a++, "flnStu");
 			DebugLib.CallStack callstack = callstack(thread);
@@ -222,10 +222,10 @@ public class DebugLib extends TwoArgFunction {
 	}
 
 	//	debug.getlocal ([thread,] f, local)
-	final class getlocal extends VarArgFunction { 
+	final class getlocal extends VarArgFunction {
 		public Varargs invoke(Varargs args) {
 			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 local = args.checkint(a++);
 			CallFrame f = callstack(thread).getCallFrame(level);
@@ -249,7 +249,7 @@ public class DebugLib extends TwoArgFunction {
 	}
 
 	//	debug.getupvalue (f, up)
-	static final class getupvalue extends VarArgFunction { 
+	static final class getupvalue extends VarArgFunction {
 		public Varargs invoke(Varargs args) {
 			LuaValue func = args.checkfunction(1);
 			int up = args.checkint(2);
@@ -265,7 +265,7 @@ public class DebugLib extends TwoArgFunction {
 	}
 
 	//	debug.getuservalue (u)
-	static final class getuservalue extends LibFunction { 
+	static final class getuservalue extends LibFunction {
 		public LuaValue call(LuaValue u) {
 			return u.isuserdata()? u: NIL;
 		}
@@ -273,10 +273,10 @@ public class DebugLib extends TwoArgFunction {
 	
 	
 	// debug.sethook ([thread,] hook, mask [, count])
-	final class sethook extends VarArgFunction { 
+	final class sethook extends VarArgFunction {
 		public Varargs invoke(Varargs args) {
 			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);
 			String str       = args.optjstring(a++,"");
 			int count        = args.optint(a++,0);
@@ -298,20 +298,20 @@ public class DebugLib extends TwoArgFunction {
 	}
 
 	//	debug.setlocal ([thread,] level, local, value)
-	final class setlocal extends VarArgFunction { 
+	final class setlocal extends VarArgFunction {
 		public Varargs invoke(Varargs args) {
 			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 local = args.checkint(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;
 		}
 	}
 
 	//	debug.setmetatable (value, table)
-	static final class setmetatable extends TwoArgFunction { 
+	static final class setmetatable extends TwoArgFunction {
 		public LuaValue call(LuaValue value, LuaValue table) {
 			LuaValue mt = table.opttable(null);
 			switch ( value.type() ) {
@@ -328,7 +328,7 @@ public class DebugLib extends TwoArgFunction {
 	}
 
 	//	debug.setupvalue (f, up, value)
-	static final class setupvalue extends VarArgFunction { 
+	static final class setupvalue extends VarArgFunction {
 		public Varargs invoke(Varargs args) {
 			LuaValue func = args.checkfunction(1);
 			int up = args.checkint(2);
@@ -346,7 +346,7 @@ public class DebugLib extends TwoArgFunction {
 	}
 
 	//	debug.setuservalue (udata, value)
-	static final class setuservalue extends VarArgFunction { 
+	static final class setuservalue extends VarArgFunction {
 		public Varargs invoke(Varargs args) {
 			Object o = args.checkuserdata(1);
 			LuaValue v = args.checkvalue(2);
@@ -358,10 +358,10 @@ public class DebugLib extends TwoArgFunction {
 	}
 	
 	//	debug.traceback ([thread,] [message [, level]])
-	final class traceback extends VarArgFunction { 
+	final class traceback extends VarArgFunction {
 		public Varargs invoke(Varargs args) {
 			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);
 			int level = args.optint(a++,1);
 			String tb = callstack(thread).traceback(level);
@@ -370,7 +370,7 @@ public class DebugLib extends TwoArgFunction {
 	}
 	
 	//	debug.upvalueid (f, n)
-	static final class upvalueid extends VarArgFunction { 
+	static final class upvalueid extends VarArgFunction {
 		public Varargs invoke(Varargs args) {
 			LuaValue func = args.checkfunction(1);
 			int up = args.checkint(2);
@@ -385,7 +385,7 @@ public class DebugLib extends TwoArgFunction {
 	}
 
 	//	debug.upvaluejoin (f1, n1, f2, n2)
-	static final class upvaluejoin extends VarArgFunction { 
+	static final class upvaluejoin extends VarArgFunction {
 		public Varargs invoke(Varargs args) {
 			LuaClosure f1 = args.checkclosure(1);
 			int n1 = args.checkint(2);
@@ -587,7 +587,7 @@ public class DebugLib extends TwoArgFunction {
 				if (frame[calls-i].f == func)
 					return frame[i];
 			return null;
-		}	
+		}
 
 
 		synchronized DebugInfo auxgetinfo(String what, LuaFunction f, CallFrame ci) {
@@ -641,7 +641,7 @@ public class DebugLib extends TwoArgFunction {
 				}
 			}
 			return ar;
-		}		
+		}
 
 	}
 
@@ -694,7 +694,7 @@ public class DebugLib extends TwoArgFunction {
 		int currentline() {
 			if ( !f.isclosure() ) return -1;
 			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() {
 			if ( !f.isclosure() ) return f.tojstring();
@@ -721,7 +721,7 @@ public class DebugLib extends TwoArgFunction {
 	
 	static void lua_assert(boolean x) {
 		if (!x) throw new RuntimeException("lua_assert failed");
-	}	
+	}
 	
 	static class NameWhat {
 		final String name;
diff --git a/src/core/org/luaj/vm2/lib/IoLib.java b/src/core/org/luaj/vm2/lib/IoLib.java
index a9d49973..fa41b7bf 100644
--- a/src/core/org/luaj/vm2/lib/IoLib.java
+++ b/src/core/org/luaj/vm2/lib/IoLib.java
@@ -31,31 +31,31 @@ import org.luaj.vm2.LuaTable;
 import org.luaj.vm2.LuaValue;
 import org.luaj.vm2.Varargs;
 
-/** 
- * Abstract base class extending {@link LibFunction} which implements the 
- * core of the lua standard {@code io} library.   
- * 

+/** + * Abstract base class extending {@link LibFunction} which implements the + * core of the lua standard {@code io} library. + *

* It contains the implementation of the io library support that is common to - * the JSE and JME platforms. - * In practice on of the concrete IOLib subclasses is chosen: - * {@link org.luaj.vm2.lib.jse.JseIoLib} for the JSE platform, and + * the JSE and JME platforms. + * 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.jme.JmeIoLib} for the JME platform. *

- * 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, - * which are difficult to support properly on JME. - *

- * Typically, this library is included as part of a call to either + * 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, + * which are difficult to support properly on JME. + *

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

 {@code
  * Globals globals = JsePlatform.standardGlobals();
  * globals.get("io").get("write").call(LuaValue.valueOf("hello, world\n"));
  * } 
* In this example the platform-specific {@link org.luaj.vm2.lib.jse.JseIoLib} library will be loaded, which will include - * the base functionality provided by this class, whereas the {@link org.luaj.vm2.lib.jse.JsePlatform} would load 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}. *

- * 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: *

 {@code
  * Globals globals = new Globals();
@@ -73,10 +73,10 @@ import org.luaj.vm2.Varargs;
  * @see org.luaj.vm2.lib.jme.JmeIoLib
  * @see http://www.lua.org/manual/5.1/manual.html#5.7
  */
-abstract 
+abstract
 public class IoLib extends TwoArgFunction {
 
-	abstract 
+	abstract
 	protected class File extends LuaValue{
 		abstract public void write( LuaString string ) throws IOException;
 		abstract public void flush() throws IOException;
@@ -85,12 +85,12 @@ public class IoLib extends TwoArgFunction {
 		abstract public boolean isclosed();
 		// returns new position
 		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
-		abstract public int remaining() throws IOException;		
+		abstract public int remaining() throws IOException;
 		// peek ahead one character
-		abstract public int peek() throws IOException, EOFException;		
-		// return char if read, -1 if eof, throw IOException on other exception 
+		abstract public int peek() throws IOException, EOFException;
+		// return char if read, -1 if eof, throw IOException on other exception
 		abstract public int read() throws IOException, EOFException;
 		// return number of bytes read if positive, false if eof, throw IOException on other exception
 		abstract public int read(byte[] bytes, int offset, int length) throws IOException;
@@ -123,29 +123,29 @@ public class IoLib extends TwoArgFunction {
 	/** Enumerated value representing a file type for a named file */
 	protected static final int FTYPE_NAMED = 3;
 
-	/** 
-	 * Wrap the standard input. 
-	 * @return File 
+	/**
+	 * Wrap the standard input.
+	 * @return File
 	 * @throws IOException
 	 */
 	abstract protected File wrapStdin() throws IOException;
 
-	/** 
-	 * Wrap the standard output. 
-	 * @return File 
+	/**
+	 * Wrap the standard output.
+	 * @return File
 	 * @throws IOException
 	 */
 	abstract protected File wrapStdout() throws IOException;
 	
-	/** 
-	 * Wrap the standard error output. 
-	 * @return File 
+	/**
+	 * Wrap the standard error output.
+	 * @return File
 	 * @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 readMode true if opening in read 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;
 
 	/**
-	 * Open a temporary file. 
+	 * Open a temporary file.
 	 * @return File object if successful
 	 * @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
 	 * @param prog the program to execute
 	 * @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
 	 */
 	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 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 CLOSED_FILE = valueOf("closed file");
 	
@@ -256,7 +256,7 @@ public class IoLib extends TwoArgFunction {
 		
 		// return the table
 		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;
 	}
 
@@ -316,7 +316,7 @@ public class IoLib extends TwoArgFunction {
 		return infile!=null? infile: (infile=ioopenfile(FTYPE_STDIN, "-","r"));
 	}
 	
-	//	io.flush() -> bool 
+	//	io.flush() -> bool
 	public Varargs _io_flush() throws IOException {
 		checkopen(output());
 		outfile.flush();
@@ -337,7 +337,7 @@ public class IoLib extends TwoArgFunction {
 
 	//	io.input([file]) -> file
 	public Varargs _io_input(LuaValue file) {
-		infile = file.isnil()? input(): 
+		infile = file.isnil()? input():
 				file.isstring()? ioopenfile(FTYPE_NAMED, file.checkjstring(),"r"):
 				checkfile(file);
 		return infile;
@@ -345,7 +345,7 @@ public class IoLib extends TwoArgFunction {
 
 	// io.output(filename) -> file
 	public Varargs _io_output(LuaValue filename) {
-		outfile = filename.isnil()? output(): 
+		outfile = filename.isnil()? output():
 				  filename.isstring()? ioopenfile(FTYPE_NAMED, filename.checkjstring(),"w"):
 				  checkfile(filename);
 		return outfile;
@@ -420,7 +420,7 @@ public class IoLib extends TwoArgFunction {
 		return valueOf( checkfile(file).seek(whence,offset) );
 	}
 
-	//	file:write(...) -> void		
+	//	file:write(...) -> void
 	public Varargs _file_write(LuaValue file, Varargs subargs) throws IOException {
 		return iowrite(checkfile(file),subargs);
 	}
@@ -468,7 +468,7 @@ public class IoLib extends TwoArgFunction {
 	}
 
 	static Varargs errorresult(Exception ioe) {
-		String s = ioe.getMessage();		
+		String s = ioe.getMessage();
 		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;
 						}
 					}
-				default: 
-					return argerror( i+1, "(invalid format)" ); 
+				default:
+					return argerror( i+1, "(invalid format)" );
 			}
 			if ( (v[i++] = vi).isnil() )
 				break;
@@ -564,7 +564,7 @@ public class IoLib extends TwoArgFunction {
 		int c;
 		try {
 			if ( lineonly ) {
-				loop: while ( (c = f.read()) > 0 ) { 
+				loop: while ( (c = f.read()) > 0 ) {
 					switch ( c ) {
 					case '\r': break;
 					case '\n': break loop;
@@ -572,13 +572,13 @@ public class IoLib extends TwoArgFunction {
 					}
 				}
 			} else {
-				while ( (c = f.read()) > 0 ) 
+				while ( (c = f.read()) > 0 )
 					baos.write(c);
 			}
 		} catch ( EOFException e ) {
 			c = -1;
 		}
-		return ( c < 0 && baos.size() == 0 )? 
+		return ( c < 0 && baos.size() == 0 )?
 			(LuaValue) NIL:
 			(LuaValue) LuaString.valueUsing(baos.toByteArray());
 	}
@@ -619,7 +619,7 @@ public class IoLib extends TwoArgFunction {
 			if ( baos != null )
 				baos.write( c );
 		}
-	}		
+	}
 	
 	
 	
diff --git a/src/core/org/luaj/vm2/lib/MathLib.java b/src/core/org/luaj/vm2/lib/MathLib.java
index 8b883aa2..7aebee77 100644
--- a/src/core/org/luaj/vm2/lib/MathLib.java
+++ b/src/core/org/luaj/vm2/lib/MathLib.java
@@ -28,13 +28,13 @@ import org.luaj.vm2.LuaTable;
 import org.luaj.vm2.LuaValue;
 import org.luaj.vm2.Varargs;
 
-/** 
- * Subclass of {@link LibFunction} which implements the lua standard {@code math} 
- * library. 
- * 

- * It contains only the math library support that is possible on JME. - * For a more complete implementation based on math functions specific to JSE - * use {@link org.luaj.vm2.lib.jse.JseMathLib}. +/** + * Subclass of {@link LibFunction} which implements the lua standard {@code math} + * library. + *

+ * It contains only the math library support that is possible on JME. + * For a more complete implementation based on math functions specific to JSE + * use {@link org.luaj.vm2.lib.jse.JseMathLib}. * In Particular the following math functions are not implemented by this library: *

    *
  • acos
  • @@ -47,21 +47,21 @@ import org.luaj.vm2.Varargs; *
  • atan2
  • *
*

- * 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. - *

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

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

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

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

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

* This has been implemented to match as closely as possible the behavior in the corresponding library in C. * @see LibFunction @@ -87,8 +87,8 @@ public class MathLib extends TwoArgFunction { */ public static MathLib MATHLIB = null; - /** Construct a MathLib, which can be initialized by calling it with a - * modname string, and a global environment table as arguments using + /** Construct a MathLib, which can be initialized by calling it with a + * modname string, and a global environment table as arguments using * {@link #call(LuaValue, LuaValue)}. */ public MathLib() { MATHLIB = this; @@ -125,7 +125,7 @@ public class MathLib extends TwoArgFunction { math.set("sqrt", new sqrt()); math.set("tan", new tan()); 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; } @@ -158,9 +158,9 @@ public class MathLib extends TwoArgFunction { exp(MathLib mathlib) { this.mathlib = mathlib; } - protected double call(double d) { - return mathlib.dpow_lib(Math.E,d); - } + protected double call(double d) { + return mathlib.dpow_lib(Math.E,d); + } } 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 */ public static LuaValue dpow(double a, double b) { - return LuaDouble.valueOf( + return LuaDouble.valueOf( MATHLIB!=null? MATHLIB.dpow_lib(a,b): dpow_default(a,b) ); } public static double dpow_d(double a, double b) { - return MATHLIB!=null? - MATHLIB.dpow_lib(a,b): + return MATHLIB!=null? + MATHLIB.dpow_lib(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) { 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) { if ( b < 0 ) diff --git a/src/core/org/luaj/vm2/lib/OsLib.java b/src/core/org/luaj/vm2/lib/OsLib.java index a114788d..85b8677e 100644 --- a/src/core/org/luaj/vm2/lib/OsLib.java +++ b/src/core/org/luaj/vm2/lib/OsLib.java @@ -35,17 +35,17 @@ import org.luaj.vm2.Varargs; * Subclass of {@link LibFunction} which implements the standard lua {@code os} library. *

* It is a usable base with simplified stub functions - * for library functions that cannot be implemented uniformly - * on Jse and Jme. + * for library functions that cannot be implemented uniformly + * on Jse and Jme. *

- * 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. *

- * Because the nature of the {@code os} library is to encapsulate - * os-specific features, the behavior of these functions varies considerably - * from their counterparts in the C platform. + * Because the nature of the {@code os} library is to encapsulate + * os-specific features, the behavior of these functions varies considerably + * from their counterparts in the C platform. *

- * The following functions have limited implementations of features + * The following functions have limited implementations of features * that are not supported well on Jme: *

    *
  • {@code execute()}
  • @@ -54,7 +54,7 @@ import org.luaj.vm2.Varargs; *
  • {@code tmpname()}
  • *
*

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

 {@code
  * 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
  * the base functionality provided by this class.
  * 

- * 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: *

 {@code
  * Globals globals = new Globals();
@@ -114,8 +114,8 @@ public class OsLib extends TwoArgFunction {
 
 	protected Globals globals;
 	
-	/** 
-	 * Create and OsLib instance.   
+	/**
+	 * Create and OsLib instance.
 	 */
 	public OsLib() {
 	}
@@ -132,7 +132,7 @@ public class OsLib extends TwoArgFunction {
 		for (int i = 0; i < NAMES.length; ++i)
 			os.set(NAMES[i], new OsLibFunc(i, NAMES[i]));
 		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;
 	}
 
@@ -200,8 +200,8 @@ public class OsLib extends TwoArgFunction {
 	}
 
 	/**
-	 * @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 
+	 * @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
 	 * OsLib class was loaded.
 	 */
 	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.
 	 * @param t2
 	 * @param t1
@@ -220,21 +220,21 @@ public class OsLib extends TwoArgFunction {
 	}
 
 	/**
-	 * If the time argument is present, this is the time to be formatted 
-	 * (see the os.time function for a description of this value). 
+	 * If the time argument is present, this is the time to be formatted
+	 * (see the os.time function for a description of this value).
 	 * Otherwise, date formats the current time.
 	 * 
-	 * Date returns the date as a string, 
+	 * Date returns the date as a string,
 	 * formatted according to the same rules as ANSII strftime, but without
 	 * support for %g, %G, or %V.
 	 * 
-	 * When called without arguments, date returns a reasonable date and 
-	 * time representation that depends on the host system and on the 
+	 * When called without arguments, date returns a reasonable date and
+	 * time representation that depends on the host system and on the
 	 * current locale (that is, os.date() is equivalent to os.date("%c")).
-	 *  
-	 * @param format 
+	 * 
+	 * @param format
 	 * @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.
 	 */
 	public String date(String format, double time) {
@@ -277,8 +277,8 @@ public class OsLib extends TwoArgFunction {
 					break;
 				case 'B':
 					result.append(MonthName[d.get(Calendar.MONTH)]);
-					break;					 
-				case 'c': 
+					break;
+				case 'c':
 					result.append(date("%a %b %d %H:%M:%S %Y", time));
 					break;
 				case 'd':
@@ -314,7 +314,7 @@ public class OsLib extends TwoArgFunction {
 				case 'w':
 					result.append(String.valueOf((d.get(Calendar.DAY_OF_WEEK)+6)%7));
 					break;
-				case 'W': 
+				case 'W':
 					result.append(String.valueOf(weekNumber(d, 1)));
 					break;
 				case 'x':
@@ -372,7 +372,7 @@ public class OsLib extends TwoArgFunction {
 	}
 	
 	private int timeZoneOffset(Calendar d) {
-		int localStandarTimeMillis = ( 
+		int localStandarTimeMillis = (
 				d.get(Calendar.HOUR_OF_DAY) * 3600 +
 				d.get(Calendar.MINUTE) * 60 +
 				d.get(Calendar.SECOND)) * 1000;
@@ -381,28 +381,28 @@ public class OsLib extends TwoArgFunction {
 				d.get(Calendar.YEAR),
 				d.get(Calendar.MONTH),
 				d.get(Calendar.DAY_OF_MONTH),
-				d.get(Calendar.DAY_OF_WEEK), 
+				d.get(Calendar.DAY_OF_WEEK),
 				localStandarTimeMillis) / 1000;
 	}
 	
 	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. 
-	 * It passes command to be executed by an operating system shell. 
-	 * It returns a status code, which is system-dependent. 
-	 * If command is absent, then it returns nonzero if a shell 
+	/**
+	 * This function is equivalent to the C function system.
+	 * It passes command to be executed by an operating system shell.
+	 * It returns a status code, which is system-dependent.
+	 * If command is absent, then it returns nonzero if a shell
 	 * is available and zero otherwise.
 	 * @param command command to pass to the system
-	 */ 
+	 */
 	protected Varargs execute(String command) {
 		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
 	 */
 	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.
 	 * 
 	 * 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
-	 * 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.
 	 * 
-	 * A SecurityException may be thrown if access is not allowed 
+	 * A SecurityException may be thrown if access is not allowed
 	 * for 'varname'.
 	 * @param varname
 	 * @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. 
-	 * Directories must be empty to be removed. 
+	 * Deletes the file or directory with the given name.
+	 * Directories must be empty to be removed.
 	 * If this function fails, it throws and IOException
-	 *  
+	 * 
 	 * @param filename
 	 * @throws IOException if it fails
 	 */
@@ -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
-	 *  
+	 * 
 	 * @param oldname old file name
 	 * @param newname new file name
 	 * @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 
-	 * a locale; category is an optional string describing which category to change: 
-	 * "all", "collate", "ctype", "monetary", "numeric", or "time"; the default category 
-	 * is "all". 
+	 * Sets the current locale of the program. locale is a string specifying
+	 * a locale; category is an optional string describing which category to change:
+	 * "all", "collate", "ctype", "monetary", "numeric", or "time"; the default category
+	 * is "all".
 	 * 
 	 * If locale is the empty string, the current locale is set to an implementation-
-	 * defined native locale. If locale is the string "C", the current locale is set 
+	 * defined native locale. If locale is the string "C", the current locale is set
 	 * to the standard C locale.
 	 * 
-	 * When called with null as the first argument, this function only returns the 
+	 * When called with null as the first argument, this function only returns the
 	 * name of the current locale for the given category.
-	 *  
+	 * 
 	 * @param locale
 	 * @param category
-	 * @return the name of the new locale, or null if the request 
+	 * @return the name of the new locale, or null if the request
 	 * cannot be honored.
 	 */
 	protected String setlocale(String locale, String category) {
@@ -477,10 +477,10 @@ public class OsLib extends TwoArgFunction {
 	}
 
 	/**
-	 * Returns the current time when called without arguments, 
-	 * or a time representing the date and time specified by the given table. 
-	 * This table must have fields year, month, and day, 
-	 * and may have fields hour, min, sec, and isdst 
+	 * Returns the current time when called without arguments,
+	 * or a time representing the date and time specified by the given table.
+	 * This table must have fields year, month, and day,
+	 * and may have fields hour, min, sec, and isdst
 	 * (for a description of these fields, see the os.date function).
 	 * @param table
 	 * @return long value for the time
@@ -504,15 +504,15 @@ public class OsLib extends TwoArgFunction {
 	}
 
 	/**
-	 * Returns a string with a file name that can be used for a temporary file. 
-	 * The file must be explicitly opened before its use and explicitly removed 
+	 * Returns a string with a file name that can be used for a temporary file.
+	 * The file must be explicitly opened before its use and explicitly removed
 	 * when no longer needed.
 	 * 
-	 * On some systems (POSIX), this function also creates a file with that name, 
-	 * to avoid security risks. (Someone else might create the file with wrong 
-	 * permissions in the time between getting the name and creating the file.) 
-	 * You still have to open the file to use it and to remove it (even if you 
-	 * do not use it). 
+	 * On some systems (POSIX), this function also creates a file with that name,
+	 * to avoid security risks. (Someone else might create the file with wrong
+	 * permissions in the time between getting the name and creating the file.)
+	 * You still have to open the file to use it and to remove it (even if you
+	 * do not use it).
 	 * 
 	 * @return String filename to use
 	 */
diff --git a/src/core/org/luaj/vm2/lib/StringLib.java b/src/core/org/luaj/vm2/lib/StringLib.java
index c87770c3..98d4c3b4 100644
--- a/src/core/org/luaj/vm2/lib/StringLib.java
+++ b/src/core/org/luaj/vm2/lib/StringLib.java
@@ -24,26 +24,26 @@ package org.luaj.vm2.lib;
 import java.io.ByteArrayOutputStream;
 import java.io.IOException;
 
-import org.luaj.vm2.LuaClosure;
 import org.luaj.vm2.Buffer;
+import org.luaj.vm2.LuaClosure;
 import org.luaj.vm2.LuaString;
 import org.luaj.vm2.LuaTable;
 import org.luaj.vm2.LuaValue;
 import org.luaj.vm2.Varargs;
 import org.luaj.vm2.compiler.DumpState;
 
-/** 
- * Subclass of {@link LibFunction} which implements the lua standard {@code string} 
- * library. 
+/**
+ * Subclass of {@link LibFunction} which implements the lua standard {@code string}
+ * library.
  * 

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

 {@code
  * Globals globals = JsePlatform.standardGlobals();
  * System.out.println( globals.get("string").get("upper").call( LuaValue.valueOf("abcde") ) );
  * } 
*

- * 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: *

 {@code
  * Globals globals = new Globals();
@@ -61,8 +61,8 @@ import org.luaj.vm2.compiler.DumpState;
  */
 public class StringLib extends TwoArgFunction {
 
-	/** Construct a StringLib, which can be initialized by calling it with a 
-	 * modname string, and a global environment table as arguments using 
+	/** Construct a StringLib, which can be initialized by calling it with a
+	 * modname string, and a global environment table as arguments using
 	 * {@link #call(LuaValue, LuaValue)}. */
 	public StringLib() {
 	}
@@ -75,8 +75,8 @@ public class StringLib extends TwoArgFunction {
 	 * If the shared strings metatable instance is null, will set the metatable as
 	 * the global shared metatable for strings.
 	 * 

- * 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 + * 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 * {@link LuaString#s_metatable} table should probably be made read-only. * @param modname the module name supplied if this is loaded via 'require'. * @param env the environment to load into, typically a Globals instance. @@ -99,7 +99,7 @@ public class StringLib extends TwoArgFunction { string.set("upper", new upper()); 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) { 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 * 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 (...) * - * Receives zero or more integers. Returns a string with length equal - * to the number of arguments, in which each character has the internal - * numerical code equal to its corresponding argument. + * Receives zero or more integers. Returns a string with length equal + * to the number of arguments, in which each character has the internal + * numerical code equal to its corresponding argument. * * Note that numerical codes are not necessarily portable across platforms. * @@ -161,15 +161,15 @@ public class StringLib extends TwoArgFunction { } } - /** + /** * string.dump (function[, stripDebug]) * - * Returns a string containing a binary representation of the given function, - * so that a later loadstring on this string returns a copy of the function. + * Returns a string containing a binary representation of the given function, + * so that a later loadstring on this string returns a copy of the function. * function must be a Lua function without upvalues. * Boolean param stripDebug - true to strip debugging info, false otherwise. * The default value for stripDebug is true. - * + * * TODO: port dumping code as optional add-on */ static final class dump extends VarArgFunction { @@ -185,20 +185,20 @@ public class StringLib extends TwoArgFunction { } } - /** + /** * string.find (s, pattern [, init [, plain]]) * - * Looks for the first match of pattern in the string s. - * If it finds a match, then find returns the indices of s - * where this occurrence starts and ends; otherwise, it returns nil. - * A third, optional numerical argument init specifies where to start the search; - * 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, - * so the function does a plain "find substring" operation, - * with no characters in pattern being considered "magic". + * Looks for the first match of pattern in the string s. + * If it finds a match, then find returns the indices of s + * where this occurrence starts and ends; otherwise, it returns nil. + * A third, optional numerical argument init specifies where to start the search; + * 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, + * so the function does a plain "find substring" operation, + * with no characters in pattern being considered "magic". * Note that if plain is given, then init must be given as well. * - * If the pattern has captures, then in a successful match the captured values + * If the pattern has captures, then in a successful match the captured values * are also returned, after the two indices. */ static final class find extends VarArgFunction { @@ -207,28 +207,28 @@ public class StringLib extends TwoArgFunction { } } - /** + /** * string.format (formatstring, ...) * - * Returns a formatted version of its variable number of arguments following - * the description given in its first argument (which must be a string). - * The format string follows the same rules as the printf family of standard C functions. - * 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 - * 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 + * Returns a formatted version of its variable number of arguments following + * the description given in its first argument (which must be a string). + * The format string follows the same rules as the printf family of standard C functions. + * 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 + * 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 * escaped when written. For instance, the call * string.format('%q', 'a string with "quotes" and \n new line') * * will produce the string: * "a string with \"quotes\" and \ * new line" - * - * The options c, d, E, e, f, g, G, i, o, u, X, and x all expect a number as argument, - * whereas q and s expect a string. * - * This function does not accept string values containing embedded zeros, - * except as arguments to the q option. + * The options c, d, E, e, f, g, G, i, o, u, X, and x all expect a number as argument, + * whereas q and s expect a string. + * + * This function does not accept string values containing embedded zeros, + * except as arguments to the q option. */ static final class format extends VarArgFunction { public Varargs invoke(Varargs args) { @@ -493,20 +493,20 @@ public class StringLib extends TwoArgFunction { } } - /** + /** * string.gmatch (s, pattern) * - * Returns an iterator function that, each time it is called, returns the next captures - * from pattern over string s. If pattern specifies no captures, then the - * whole match is produced in each call. + * Returns an iterator function that, each time it is called, returns the next captures + * from pattern over string s. If pattern specifies no captures, then the + * whole match is produced in each call. * * As an example, the following loop * s = "hello world from Lua" * for w in string.gmatch(s, "%a+") do * print(w) * end - * - * will iterate over all the words from string s, printing one per line. + * + * will iterate over all the words from string s, printing one per line. * The next example collects all pairs key=value from the given string into a table: * t = {} * s = "from=world, to=Lua" @@ -514,7 +514,7 @@ public class StringLib extends TwoArgFunction { * t[k] = v * 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. */ static final class gmatch extends VarArgFunction { @@ -550,28 +550,28 @@ public class StringLib extends TwoArgFunction { } - /** + /** * string.gsub (s, pattern, repl [, n]) - * 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 - * may be a string, a table, or a function. gsub also returns, as its second value, + * 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 + * may be a string, a table, or a function. gsub also returns, as its second value, * the total number of matches that occurred. * - * If repl is a string, then its value is used for replacement. - * The character % works as an escape character: any sequence in repl of the form %n, - * with n between 1 and 9, stands for the value of the n-th captured substring (see below). - * The sequence %0 stands for the whole match. The sequence %% stands for a single %. - * - * If repl is a table, then the table is queried for every match, using the first capture - * as the key; if the pattern specifies no captures, then the whole match is used as the key. + * If repl is a string, then its value is used for replacement. + * The character % works as an escape character: any sequence in repl of the form %n, + * with n between 1 and 9, stands for the value of the n-th captured substring (see below). + * The sequence %0 stands for the whole match. The sequence %% stands for a single %. * - * If repl is a function, then this function is called every time a match occurs, - * with all captured substrings passed as arguments, in order; if the pattern specifies - * no captures, then the whole match is passed as a sole argument. + * If 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 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). + * If repl is a function, then this function is called every time a match occurs, + * with all captured substrings passed as arguments, in order; if the pattern specifies + * no captures, then the whole match is passed as a sole argument. + * + * If the value returned by the table query or by the function call is a string or a number, + * then it is used as the replacement string; otherwise, if it is false or nil, + * then there is no replacement (that is, the original match is kept in the string). * * Here are some examples: * x = string.gsub("hello world", "(%w+)", "%1 %1") @@ -630,11 +630,11 @@ public class StringLib extends TwoArgFunction { } } - /** + /** * string.len (s) * - * Receives a string and returns its length. The empty string "" has length 0. - * Embedded zeros are counted, so "a\000bc\000" has length 5. + * Receives a string and returns its length. The empty string "" has length 0. + * Embedded zeros are counted, so "a\000bc\000" has length 5. */ static final class len extends OneArgFunction { public LuaValue call(LuaValue arg) { @@ -642,11 +642,11 @@ public class StringLib extends TwoArgFunction { } } - /** + /** * string.lower (s) * - * Receives a string and returns a copy of this string with all uppercase letters - * changed to lowercase. All other characters are left unchanged. + * Receives a string and returns a copy of this string with all uppercase letters + * changed to lowercase. All other characters are left unchanged. * The definition of what an uppercase letter is depends on the current locale. */ static final class lower extends OneArgFunction { @@ -673,7 +673,7 @@ public class StringLib extends TwoArgFunction { /** * 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 { public Varargs invoke(Varargs args) { @@ -688,10 +688,10 @@ public class StringLib extends TwoArgFunction { } } - /** + /** * 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 { public LuaValue call(LuaValue arg) { @@ -704,15 +704,15 @@ public class StringLib extends TwoArgFunction { } } - /** + /** * string.sub (s, i [, j]) * - * Returns the substring of s that starts at i and continues until j; - * i and j may be negative. If j is absent, then it is assumed to be equal to -1 - * (which is the same as the string length). In particular, the call - * string.sub(s,1,j) - * returns a prefix of s with length j, and - * string.sub(s, -i) + * Returns the substring of s that starts at i and continues until j; + * i and j may be negative. If j is absent, then it is assumed to be equal to -1 + * (which is the same as the string length). In particular, the call + * string.sub(s,1,j) + * returns a prefix of s with length j, and + * string.sub(s, -i) * returns a suffix of s with length i. */ static final class sub extends VarArgFunction { @@ -736,12 +736,12 @@ public class StringLib extends TwoArgFunction { } } - /** + /** * string.upper (s) * - * Receives a string and returns a copy of this string with all lowercase letters - * changed to uppercase. All other characters are left unchanged. - * The definition of what a lowercase letter is depends on the current locale. + * Receives a string and returns a copy of this string with all lowercase letters + * changed to uppercase. All other characters are left unchanged. + * The definition of what a lowercase letter is depends on the current locale. */ static final class upper extends OneArgFunction { public LuaValue call(LuaValue arg) { @@ -1055,7 +1055,7 @@ public class StringLib extends TwoArgFunction { */ int match( int soffset, int poffset ) { 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 // string is not NUL-terminated. if ( poffset == p.length() ) diff --git a/src/core/org/luaj/vm2/lib/TableLib.java b/src/core/org/luaj/vm2/lib/TableLib.java index bc613676..74456952 100644 --- a/src/core/org/luaj/vm2/lib/TableLib.java +++ b/src/core/org/luaj/vm2/lib/TableLib.java @@ -25,19 +25,19 @@ import org.luaj.vm2.LuaTable; import org.luaj.vm2.LuaValue; import org.luaj.vm2.Varargs; -/** - * Subclass of {@link LibFunction} which implements the lua standard {@code table} - * library. +/** + * Subclass of {@link LibFunction} which implements the lua standard {@code table} + * library. * *

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

 {@code
  * Globals globals = JsePlatform.standardGlobals();
  * System.out.println( globals.get("table").get("length").call( LuaValue.tableOf() ) );
  * } 
*

- * 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: *

 {@code
  * Globals globals = new Globals();
@@ -70,7 +70,7 @@ public class TableLib extends TwoArgFunction {
 		table.set("sort", new sort());
 		table.set("unpack", new unpack());
 		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;
 	}
 
diff --git a/src/jse/org/luaj/vm2/lib/jse/LuajavaLib.java b/src/jse/org/luaj/vm2/lib/jse/LuajavaLib.java
index 7b4d16ea..35f1f850 100644
--- a/src/jse/org/luaj/vm2/lib/jse/LuajavaLib.java
+++ b/src/jse/org/luaj/vm2/lib/jse/LuajavaLib.java
@@ -37,38 +37,38 @@ import org.luaj.vm2.compiler.LuaC;
 import org.luaj.vm2.lib.LibFunction;
 import org.luaj.vm2.lib.VarArgFunction;
 
-/** 
- * Subclass of {@link LibFunction} which implements the features of the luajava package. 
- * 

- * 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 +/** + * Subclass of {@link LibFunction} which implements the features of the luajava package. + *

+ * 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 * luajava documentation pages. * *

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

 {@code
  * Globals globals = JsePlatform.standardGlobals();
  * System.out.println( globals.get("luajava").get("bindClass").call( LuaValue.valueOf("java.lang.System") ).invokeMethod("currentTimeMillis") );
  * } 
*

- * 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: *

 {@code
  * Globals globals = new Globals();
  * globals.load(new JseBaseLib());
  * globals.load(new PackageLib());
  * globals.load(new LuajavaLib());
- * globals.load( 
+ * globals.load(
  *      "sys = luajava.bindClass('java.lang.System')\n"+
- *      "print ( sys:currentTimeMillis() )\n", "main.lua" ).call(); 
+ *      "print ( sys:currentTimeMillis() )\n", "main.lua" ).call();
  * } 
*

* - * 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()} - * and the luajava api's are simply invoked from lua. - * Because it makes extensive use of Java's reflection API, it is not available + * and the luajava api's are simply invoked from lua. + * Because it makes extensive use of Java's reflection API, it is not available * on JME, but can be used in Android applications. *

* 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 String[] NAMES = { - "bindClass", - "newInstance", - "new", - "createProxy", + "bindClass", + "newInstance", + "new", + "createProxy", "loadLib", }; @@ -112,7 +112,7 @@ public class LuajavaLib extends VarArgFunction { LuaTable t = new LuaTable(); bind( t, this.getClass(), NAMES, BINDCLASS ); 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; } case BINDCLASS: { @@ -122,13 +122,13 @@ public class LuajavaLib extends VarArgFunction { case NEWINSTANCE: case NEW: { // 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 Varargs consargs = args.subargs(2); return JavaClass.forClass(clazz).getConstructor().invoke(consargs); } - case CREATEPROXY: { + case CREATEPROXY: { final int niface = args.narg()-1; if ( niface <= 0 ) throw new LuaError("no interfaces"); @@ -136,7 +136,7 @@ public class LuajavaLib extends VarArgFunction { // get the interfaces final Class[] ifaces = new Class[niface]; - for ( int i=0; i