Fix lua error message on bad arg for 'load'.

This commit is contained in:
Enyby
2019-09-21 07:18:08 +03:00
parent 6d2deb4cb6
commit 6031d6b479

View File

@@ -1,484 +1,486 @@
/******************************************************************************* /*******************************************************************************
* Copyright (c) 2009 Luaj.org. All rights reserved. * Copyright (c) 2009 Luaj.org. All rights reserved.
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy * Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal * of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights * in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is * copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions: * furnished to do so, subject to the following conditions:
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE. * THE SOFTWARE.
******************************************************************************/ ******************************************************************************/
package org.luaj.vm2.lib; package org.luaj.vm2.lib;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import org.luaj.vm2.Globals; import org.luaj.vm2.Globals;
import org.luaj.vm2.Lua; import org.luaj.vm2.Lua;
import org.luaj.vm2.LuaError; import org.luaj.vm2.LuaError;
import org.luaj.vm2.LuaString; import org.luaj.vm2.LuaString;
import org.luaj.vm2.LuaTable; import org.luaj.vm2.LuaTable;
import org.luaj.vm2.LuaThread; 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 basic library functions. * Subclass of {@link LibFunction} which implements the lua basic library functions.
* <p> * <p>
* This contains all library functions listed as "basic functions" in the lua documentation for JME. * This contains all library functions listed as "basic functions" in the lua documentation for JME.
* The functions dofile and loadfile use the * The functions dofile and loadfile use the
* {@link Globals#finder} instance to find resource files. * {@link Globals#finder} instance to find resource files.
* Since JME has no file system by default, {@link BaseLib} implements * Since JME has no file system by default, {@link BaseLib} implements
* {@link ResourceFinder} using {@link Class#getResource(String)}, * {@link ResourceFinder} using {@link Class#getResource(String)},
* which is the closest equivalent on JME. * which is the closest equivalent on JME.
* The default loader chain in {@link PackageLib} will use these as well. * The default loader chain in {@link PackageLib} will use these as well.
* <p> * <p>
* To use basic library functions that include a {@link ResourceFinder} based on * To use basic library functions that include a {@link ResourceFinder} based on
* directory lookup, use {@link org.luaj.vm2.lib.jse.JseBaseLib} instead. * directory lookup, use {@link org.luaj.vm2.lib.jse.JseBaseLib} instead.
* <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();
* globals.get("print").call(LuaValue.valueOf("hello, world")); * globals.get("print").call(LuaValue.valueOf("hello, world"));
* } </pre> * } </pre>
* <p> * <p>
* For special cases where the smallest possible footprint is desired, * For special cases where the smallest possible footprint is desired,
* a minimal set of libraries could be loaded * a minimal set of libraries could be loaded
* directly via {@link Globals#load(LuaValue)} using code such as: * directly via {@link Globals#load(LuaValue)} 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.get("print").call(LuaValue.valueOf("hello, world")); * globals.get("print").call(LuaValue.valueOf("hello, world"));
* } </pre> * } </pre>
* Doing so will ensure the library is properly initialized * Doing so will ensure the library is properly initialized
* and loaded into the globals table. * and loaded into the globals table.
* <p> * <p>
* This is a direct port of the corresponding library in C. * This is a direct port of the corresponding library in C.
* @see org.luaj.vm2.lib.jse.JseBaseLib * @see org.luaj.vm2.lib.jse.JseBaseLib
* @see ResourceFinder * @see ResourceFinder
* @see Globals#finder * @see Globals#finder
* @see LibFunction * @see LibFunction
* @see org.luaj.vm2.lib.jse.JsePlatform * @see org.luaj.vm2.lib.jse.JsePlatform
* @see org.luaj.vm2.lib.jme.JmePlatform * @see org.luaj.vm2.lib.jme.JmePlatform
* @see <a href="http://www.lua.org/manual/5.2/manual.html#6.1">Lua 5.2 Base Lib Reference</a> * @see <a href="http://www.lua.org/manual/5.2/manual.html#6.1">Lua 5.2 Base Lib Reference</a>
*/ */
public class BaseLib extends TwoArgFunction implements ResourceFinder { public class BaseLib extends TwoArgFunction implements ResourceFinder {
Globals globals; Globals globals;
/** Perform one-time initialization on the library by adding base functions /** Perform one-time initialization on the library by adding base functions
* to the supplied environment, and returning it as the return value. * to the supplied environment, and returning it as the return value.
* @param modname the module name supplied if this is loaded via 'require'. * @param modname the module name supplied if this is loaded via 'require'.
* @param env the environment to load into, which must be a Globals instance. * @param env the environment to load into, which must be a Globals instance.
*/ */
public LuaValue call(LuaValue modname, LuaValue env) { public LuaValue call(LuaValue modname, LuaValue env) {
globals = env.checkglobals(); globals = env.checkglobals();
globals.finder = this; globals.finder = this;
globals.baselib = this; globals.baselib = this;
env.set( "_G", env ); env.set( "_G", env );
env.set( "_VERSION", Lua._VERSION ); env.set( "_VERSION", Lua._VERSION );
env.set("assert", new _assert()); env.set("assert", new _assert());
env.set("collectgarbage", new collectgarbage()); env.set("collectgarbage", new collectgarbage());
env.set("dofile", new dofile()); env.set("dofile", new dofile());
env.set("error", new error()); env.set("error", new error());
env.set("getmetatable", new getmetatable()); env.set("getmetatable", new getmetatable());
env.set("load", new load()); env.set("load", new load());
env.set("loadfile", new loadfile()); env.set("loadfile", new loadfile());
env.set("pcall", new pcall()); env.set("pcall", new pcall());
env.set("print", new print(this)); env.set("print", new print(this));
env.set("rawequal", new rawequal()); env.set("rawequal", new rawequal());
env.set("rawget", new rawget()); env.set("rawget", new rawget());
env.set("rawlen", new rawlen()); env.set("rawlen", new rawlen());
env.set("rawset", new rawset()); env.set("rawset", new rawset());
env.set("select", new select()); env.set("select", new select());
env.set("setmetatable", new setmetatable()); env.set("setmetatable", new setmetatable());
env.set("tonumber", new tonumber()); env.set("tonumber", new tonumber());
env.set("tostring", new tostring()); env.set("tostring", new tostring());
env.set("type", new type()); env.set("type", new type());
env.set("xpcall", new xpcall()); env.set("xpcall", new xpcall());
next next; next next;
env.set("next", next = new next()); env.set("next", next = new next());
env.set("pairs", new pairs(next)); env.set("pairs", new pairs(next));
env.set("ipairs", new ipairs()); env.set("ipairs", new ipairs());
return env; return env;
} }
/** ResourceFinder implementation /** ResourceFinder implementation
* *
* Tries to open the file as a resource, which can work for JSE and JME. * Tries to open the file as a resource, which can work for JSE and JME.
*/ */
public InputStream findResource(String filename) { public InputStream findResource(String filename) {
return getClass().getResourceAsStream(filename.startsWith("/")? filename: "/"+filename); return getClass().getResourceAsStream(filename.startsWith("/")? filename: "/"+filename);
} }
// "assert", // ( v [,message] ) -> v, message | ERR // "assert", // ( v [,message] ) -> v, message | ERR
static final class _assert extends VarArgFunction { static final class _assert extends VarArgFunction {
public Varargs invoke(Varargs args) { public Varargs invoke(Varargs args) {
if ( !args.arg1().toboolean() ) if ( !args.arg1().toboolean() )
error( args.narg()>1? args.optjstring(2,"assertion failed!"): "assertion failed!" ); error( args.narg()>1? args.optjstring(2,"assertion failed!"): "assertion failed!" );
return args; return args;
} }
} }
// "collectgarbage", // ( opt [,arg] ) -> value // "collectgarbage", // ( opt [,arg] ) -> value
static final class collectgarbage extends VarArgFunction { static final class collectgarbage extends VarArgFunction {
public Varargs invoke(Varargs args) { public Varargs invoke(Varargs args) {
String s = args.optjstring(1, "collect"); String s = args.optjstring(1, "collect");
if ( "collect".equals(s) ) { if ( "collect".equals(s) ) {
System.gc(); System.gc();
return ZERO; return ZERO;
} else if ( "count".equals(s) ) { } else if ( "count".equals(s) ) {
Runtime rt = Runtime.getRuntime(); Runtime rt = Runtime.getRuntime();
long used = rt.totalMemory() - rt.freeMemory(); long used = rt.totalMemory() - rt.freeMemory();
return varargsOf(valueOf(used/1024.), valueOf(used%1024)); return varargsOf(valueOf(used/1024.), valueOf(used%1024));
} else if ( "step".equals(s) ) { } else if ( "step".equals(s) ) {
System.gc(); System.gc();
return LuaValue.TRUE; return LuaValue.TRUE;
} else { } else {
this.argerror("gc op"); this.argerror("gc op");
} }
return NIL; return NIL;
} }
} }
// "dofile", // ( filename ) -> result1, ... // "dofile", // ( filename ) -> result1, ...
final class dofile extends VarArgFunction { final class dofile extends VarArgFunction {
public Varargs invoke(Varargs args) { public Varargs invoke(Varargs args) {
args.argcheck(args.isstring(1) || args.isnil(1), 1, "filename must be string or nil"); args.argcheck(args.isstring(1) || args.isnil(1), 1, "filename must be string or nil");
String filename = args.isstring(1)? args.tojstring(1): null; String filename = args.isstring(1)? args.tojstring(1): null;
Varargs v = filename == null? Varargs v = filename == null?
loadStream( globals.STDIN, "=stdin", "bt", globals ): loadStream( globals.STDIN, "=stdin", "bt", globals ):
loadFile( args.checkjstring(1), "bt", globals ); loadFile( args.checkjstring(1), "bt", globals );
return v.isnil(1)? error(v.tojstring(2)): v.arg1().invoke(); return v.isnil(1)? error(v.tojstring(2)): v.arg1().invoke();
} }
} }
// "error", // ( message [,level] ) -> ERR // "error", // ( message [,level] ) -> ERR
static final class error extends TwoArgFunction { static final class error extends TwoArgFunction {
public LuaValue call(LuaValue arg1, LuaValue arg2) { public LuaValue call(LuaValue arg1, LuaValue arg2) {
throw arg1.isnil()? new LuaError(null, arg2.optint(1)): throw arg1.isnil()? new LuaError(null, arg2.optint(1)):
arg1.isstring()? new LuaError(arg1.tojstring(), arg2.optint(1)): arg1.isstring()? new LuaError(arg1.tojstring(), arg2.optint(1)):
new LuaError(arg1); new LuaError(arg1);
} }
} }
// "getmetatable", // ( object ) -> table // "getmetatable", // ( object ) -> table
static final class getmetatable extends LibFunction { static final class getmetatable extends LibFunction {
public LuaValue call() { public LuaValue call() {
return argerror(1, "value"); return argerror(1, "value");
} }
public LuaValue call(LuaValue arg) { public LuaValue call(LuaValue arg) {
LuaValue mt = arg.getmetatable(); LuaValue mt = arg.getmetatable();
return mt!=null? mt.rawget(METATABLE).optvalue(mt): NIL; return mt!=null? mt.rawget(METATABLE).optvalue(mt): NIL;
} }
} }
// "load", // ( ld [, source [, mode [, env]]] ) -> chunk | nil, msg // "load", // ( ld [, source [, mode [, env]]] ) -> chunk | nil, msg
final class load extends VarArgFunction { final class load extends VarArgFunction {
public Varargs invoke(Varargs args) { public Varargs invoke(Varargs args) {
LuaValue ld = args.arg1(); LuaValue ld = args.arg1();
args.argcheck(ld.isstring() || ld.isfunction(), 1, "ld must be string or function"); if (!ld.isstring() && !ld.isfunction()) {
String source = args.optjstring(2, ld.isstring()? ld.tojstring(): "=(load)"); throw new LuaError("bad argument #1 to 'load' (string or function expected, got " + ld.typename() + ")");
String mode = args.optjstring(3, "bt"); }
LuaValue env = args.optvalue(4, globals); String source = args.optjstring(2, ld.isstring()? ld.tojstring(): "=(load)");
return loadStream(ld.isstring()? ld.strvalue().toInputStream(): String mode = args.optjstring(3, "bt");
new StringInputStream(ld.checkfunction()), source, mode, env); LuaValue env = args.optvalue(4, globals);
} return loadStream(ld.isstring()? ld.strvalue().toInputStream():
} new StringInputStream(ld.checkfunction()), source, mode, env);
}
// "loadfile", // ( [filename [, mode [, env]]] ) -> chunk | nil, msg }
final class loadfile extends VarArgFunction {
public Varargs invoke(Varargs args) { // "loadfile", // ( [filename [, mode [, env]]] ) -> chunk | nil, msg
args.argcheck(args.isstring(1) || args.isnil(1), 1, "filename must be string or nil"); final class loadfile extends VarArgFunction {
String filename = args.isstring(1)? args.tojstring(1): null; public Varargs invoke(Varargs args) {
String mode = args.optjstring(2, "bt"); args.argcheck(args.isstring(1) || args.isnil(1), 1, "filename must be string or nil");
LuaValue env = args.optvalue(3, globals); String filename = args.isstring(1)? args.tojstring(1): null;
return filename == null? String mode = args.optjstring(2, "bt");
loadStream( globals.STDIN, "=stdin", mode, env ): LuaValue env = args.optvalue(3, globals);
loadFile( filename, mode, env ); return filename == null?
} loadStream( globals.STDIN, "=stdin", mode, env ):
} loadFile( filename, mode, env );
}
// "pcall", // (f, arg1, ...) -> status, result1, ... }
final class pcall extends VarArgFunction {
public Varargs invoke(Varargs args) { // "pcall", // (f, arg1, ...) -> status, result1, ...
LuaValue func = args.checkvalue(1); final class pcall extends VarArgFunction {
if (globals != null && globals.debuglib != null) public Varargs invoke(Varargs args) {
globals.debuglib.onCall(this); LuaValue func = args.checkvalue(1);
try { if (globals != null && globals.debuglib != null)
return varargsOf(TRUE, func.invoke(args.subargs(2))); globals.debuglib.onCall(this);
} catch ( LuaError le ) { try {
final LuaValue m = le.getMessageObject(); return varargsOf(TRUE, func.invoke(args.subargs(2)));
return varargsOf(FALSE, m!=null? m: NIL); } catch ( LuaError le ) {
} catch ( Exception e ) { final LuaValue m = le.getMessageObject();
final String m = e.getMessage(); return varargsOf(FALSE, m!=null? m: NIL);
return varargsOf(FALSE, valueOf(m!=null? m: e.toString())); } catch ( Exception e ) {
} finally { final String m = e.getMessage();
if (globals != null && globals.debuglib != null) return varargsOf(FALSE, valueOf(m!=null? m: e.toString()));
globals.debuglib.onReturn(); } finally {
} if (globals != null && globals.debuglib != null)
} globals.debuglib.onReturn();
} }
}
// "print", // (...) -> void }
final class print extends VarArgFunction {
final BaseLib baselib; // "print", // (...) -> void
print(BaseLib baselib) { final class print extends VarArgFunction {
this.baselib = baselib; final BaseLib baselib;
} print(BaseLib baselib) {
public Varargs invoke(Varargs args) { this.baselib = baselib;
LuaValue tostring = globals.get("tostring"); }
for ( int i=1, n=args.narg(); i<=n; i++ ) { public Varargs invoke(Varargs args) {
if ( i>1 ) globals.STDOUT.print( '\t' ); LuaValue tostring = globals.get("tostring");
LuaString s = tostring.call( args.arg(i) ).strvalue(); for ( int i=1, n=args.narg(); i<=n; i++ ) {
globals.STDOUT.print(s.tojstring()); if ( i>1 ) globals.STDOUT.print( '\t' );
} LuaString s = tostring.call( args.arg(i) ).strvalue();
globals.STDOUT.print('\n'); globals.STDOUT.print(s.tojstring());
return NONE; }
} globals.STDOUT.print('\n');
} return NONE;
}
}
// "rawequal", // (v1, v2) -> boolean
static final class rawequal extends LibFunction {
public LuaValue call() { // "rawequal", // (v1, v2) -> boolean
return argerror(1, "value"); static final class rawequal extends LibFunction {
} public LuaValue call() {
public LuaValue call(LuaValue arg) { return argerror(1, "value");
return argerror(2, "value"); }
} public LuaValue call(LuaValue arg) {
public LuaValue call(LuaValue arg1, LuaValue arg2) { return argerror(2, "value");
return valueOf(arg1.raweq(arg2)); }
} public LuaValue call(LuaValue arg1, LuaValue arg2) {
} return valueOf(arg1.raweq(arg2));
}
// "rawget", // (table, index) -> value }
static final class rawget extends LibFunction {
public LuaValue call() { // "rawget", // (table, index) -> value
return argerror(1, "value"); static final class rawget extends LibFunction {
} public LuaValue call() {
public LuaValue call(LuaValue arg) { return argerror(1, "value");
return argerror(2, "value"); }
} public LuaValue call(LuaValue arg) {
public LuaValue call(LuaValue arg1, LuaValue arg2) { return argerror(2, "value");
return arg1.checktable().rawget(arg2); }
} public LuaValue call(LuaValue arg1, LuaValue arg2) {
} return arg1.checktable().rawget(arg2);
}
}
// "rawlen", // (v) -> value
static final class rawlen extends LibFunction {
public LuaValue call(LuaValue arg) { // "rawlen", // (v) -> value
return valueOf(arg.rawlen()); static final class rawlen extends LibFunction {
} public LuaValue call(LuaValue arg) {
} return valueOf(arg.rawlen());
}
// "rawset", // (table, index, value) -> table }
static final class rawset extends LibFunction {
public LuaValue call(LuaValue table) { // "rawset", // (table, index, value) -> table
return argerror(2,"value"); static final class rawset extends LibFunction {
} public LuaValue call(LuaValue table) {
public LuaValue call(LuaValue table, LuaValue index) { return argerror(2,"value");
return argerror(3,"value"); }
} public LuaValue call(LuaValue table, LuaValue index) {
public LuaValue call(LuaValue table, LuaValue index, LuaValue value) { return argerror(3,"value");
LuaTable t = table.checktable(); }
if (!index.isvalidkey()) argerror(2, "value"); public LuaValue call(LuaValue table, LuaValue index, LuaValue value) {
t.rawset(index, value); LuaTable t = table.checktable();
return t; if (!index.isvalidkey()) argerror(2, "value");
} t.rawset(index, value);
} return t;
}
// "select", // (f, ...) -> value1, ... }
static final class select extends VarArgFunction {
public Varargs invoke(Varargs args) { // "select", // (f, ...) -> value1, ...
int n = args.narg()-1; static final class select extends VarArgFunction {
if ( args.arg1().equals(valueOf("#")) ) public Varargs invoke(Varargs args) {
return valueOf(n); int n = args.narg()-1;
int i = args.checkint(1); if ( args.arg1().equals(valueOf("#")) )
if ( i == 0 || i < -n ) return valueOf(n);
argerror(1,"index out of range"); int i = args.checkint(1);
return args.subargs(i<0? n+i+2: i+1); if ( i == 0 || i < -n )
} argerror(1,"index out of range");
} return args.subargs(i<0? n+i+2: i+1);
}
// "setmetatable", // (table, metatable) -> table }
static final class setmetatable extends LibFunction {
public LuaValue call(LuaValue table) { // "setmetatable", // (table, metatable) -> table
return argerror(2,"value"); static final class setmetatable extends LibFunction {
} public LuaValue call(LuaValue table) {
public LuaValue call(LuaValue table, LuaValue metatable) { return argerror(2,"value");
final LuaValue mt0 = table.checktable().getmetatable(); }
if ( mt0!=null && !mt0.rawget(METATABLE).isnil() ) public LuaValue call(LuaValue table, LuaValue metatable) {
error("cannot change a protected metatable"); final LuaValue mt0 = table.checktable().getmetatable();
return table.setmetatable(metatable.isnil()? null: metatable.checktable()); if ( mt0!=null && !mt0.rawget(METATABLE).isnil() )
} error("cannot change a protected metatable");
} return table.setmetatable(metatable.isnil()? null: metatable.checktable());
}
// "tonumber", // (e [,base]) -> value }
static final class tonumber extends LibFunction {
public LuaValue call(LuaValue e) { // "tonumber", // (e [,base]) -> value
return e.tonumber(); static final class tonumber extends LibFunction {
} public LuaValue call(LuaValue e) {
public LuaValue call(LuaValue e, LuaValue base) { return e.tonumber();
if (base.isnil()) }
return e.tonumber(); public LuaValue call(LuaValue e, LuaValue base) {
final int b = base.checkint(); if (base.isnil())
if ( b < 2 || b > 36 ) return e.tonumber();
argerror(2, "base out of range"); final int b = base.checkint();
return e.checkstring().tonumber(b); if ( b < 2 || b > 36 )
} argerror(2, "base out of range");
} return e.checkstring().tonumber(b);
}
// "tostring", // (e) -> value }
static final class tostring extends LibFunction {
public LuaValue call(LuaValue arg) { // "tostring", // (e) -> value
LuaValue h = arg.metatag(TOSTRING); static final class tostring extends LibFunction {
if ( ! h.isnil() ) public LuaValue call(LuaValue arg) {
return h.call(arg); LuaValue h = arg.metatag(TOSTRING);
LuaValue v = arg.tostring(); if ( ! h.isnil() )
if ( ! v.isnil() ) return h.call(arg);
return v; LuaValue v = arg.tostring();
return valueOf(arg.tojstring()); if ( ! v.isnil() )
} return v;
} return valueOf(arg.tojstring());
}
// "type", // (v) -> value }
static final class type extends LibFunction {
public LuaValue call(LuaValue arg) { // "type", // (v) -> value
return valueOf(arg.typename()); static final class type extends LibFunction {
} public LuaValue call(LuaValue arg) {
} return valueOf(arg.typename());
}
// "xpcall", // (f, err) -> result1, ... }
final class xpcall extends VarArgFunction {
public Varargs invoke(Varargs args) { // "xpcall", // (f, err) -> result1, ...
final LuaThread t = globals.running; final class xpcall extends VarArgFunction {
final LuaValue preverror = t.errorfunc; public Varargs invoke(Varargs args) {
t.errorfunc = args.checkvalue(2); final LuaThread t = globals.running;
try { final LuaValue preverror = t.errorfunc;
if (globals != null && globals.debuglib != null) t.errorfunc = args.checkvalue(2);
globals.debuglib.onCall(this); try {
try { if (globals != null && globals.debuglib != null)
return varargsOf(TRUE, args.arg1().invoke(args.subargs(3))); globals.debuglib.onCall(this);
} catch ( LuaError le ) { try {
final LuaValue m = le.getMessageObject(); return varargsOf(TRUE, args.arg1().invoke(args.subargs(3)));
return varargsOf(FALSE, m!=null? m: NIL); } catch ( LuaError le ) {
} catch ( Exception e ) { final LuaValue m = le.getMessageObject();
final String m = e.getMessage(); return varargsOf(FALSE, m!=null? m: NIL);
return varargsOf(FALSE, valueOf(m!=null? m: e.toString())); } catch ( Exception e ) {
} finally { final String m = e.getMessage();
if (globals != null && globals.debuglib != null) return varargsOf(FALSE, valueOf(m!=null? m: e.toString()));
globals.debuglib.onReturn(); } finally {
} if (globals != null && globals.debuglib != null)
} finally { globals.debuglib.onReturn();
t.errorfunc = preverror; }
} } finally {
} t.errorfunc = preverror;
} }
}
// "pairs" (t) -> iter-func, t, nil }
static final class pairs extends VarArgFunction {
final next next; // "pairs" (t) -> iter-func, t, nil
pairs(next next) { static final class pairs extends VarArgFunction {
this.next = next; final next next;
} pairs(next next) {
public Varargs invoke(Varargs args) { this.next = next;
return varargsOf( next, args.checktable(1), NIL ); }
} public Varargs invoke(Varargs args) {
} return varargsOf( next, args.checktable(1), NIL );
}
// // "ipairs", // (t) -> iter-func, t, 0 }
static final class ipairs extends VarArgFunction {
inext inext = new inext(); // // "ipairs", // (t) -> iter-func, t, 0
public Varargs invoke(Varargs args) { static final class ipairs extends VarArgFunction {
return varargsOf( inext, args.checktable(1), ZERO ); inext inext = new inext();
} public Varargs invoke(Varargs args) {
} return varargsOf( inext, args.checktable(1), ZERO );
}
// "next" ( table, [index] ) -> next-index, next-value }
static final class next extends VarArgFunction {
public Varargs invoke(Varargs args) { // "next" ( table, [index] ) -> next-index, next-value
return args.checktable(1).next(args.arg(2)); static final class next extends VarArgFunction {
} public Varargs invoke(Varargs args) {
} return args.checktable(1).next(args.arg(2));
}
// "inext" ( table, [int-index] ) -> next-index, next-value }
static final class inext extends VarArgFunction {
public Varargs invoke(Varargs args) { // "inext" ( table, [int-index] ) -> next-index, next-value
return args.checktable(1).inext(args.arg(2)); static final class inext extends VarArgFunction {
} public Varargs invoke(Varargs args) {
} return args.checktable(1).inext(args.arg(2));
}
/** }
* Load from a named file, returning the chunk or nil,error of can't load
* @param env /**
* @param mode * Load from a named file, returning the chunk or nil,error of can't load
* @return Varargs containing chunk, or NIL,error-text on error * @param env
*/ * @param mode
public Varargs loadFile(String filename, String mode, LuaValue env) { * @return Varargs containing chunk, or NIL,error-text on error
InputStream is = globals.finder.findResource(filename); */
if ( is == null ) public Varargs loadFile(String filename, String mode, LuaValue env) {
return varargsOf(NIL, valueOf("cannot open "+filename+": No such file or directory")); InputStream is = globals.finder.findResource(filename);
try { if ( is == null )
return loadStream(is, "@"+filename, mode, env); return varargsOf(NIL, valueOf("cannot open "+filename+": No such file or directory"));
} finally { try {
try { return loadStream(is, "@"+filename, mode, env);
is.close(); } finally {
} catch ( Exception e ) { try {
e.printStackTrace(); is.close();
} } catch ( Exception e ) {
} e.printStackTrace();
} }
}
public Varargs loadStream(InputStream is, String chunkname, String mode, LuaValue env) { }
try {
if ( is == null ) public Varargs loadStream(InputStream is, String chunkname, String mode, LuaValue env) {
return varargsOf(NIL, valueOf("not found: "+chunkname)); try {
return globals.load(is, chunkname, mode, env); if ( is == null )
} catch (Exception e) { return varargsOf(NIL, valueOf("not found: "+chunkname));
return varargsOf(NIL, valueOf(e.getMessage())); return globals.load(is, chunkname, mode, env);
} } catch (Exception e) {
} return varargsOf(NIL, valueOf(e.getMessage()));
}
}
private static class StringInputStream extends InputStream {
final LuaValue func;
byte[] bytes; private static class StringInputStream extends InputStream {
int offset, remaining = 0; final LuaValue func;
StringInputStream(LuaValue func) { byte[] bytes;
this.func = func; int offset, remaining = 0;
} StringInputStream(LuaValue func) {
public int read() throws IOException { this.func = func;
if ( remaining <= 0 ) { }
LuaValue s = func.call(); public int read() throws IOException {
if ( s.isnil() ) if ( remaining <= 0 ) {
return -1; LuaValue s = func.call();
LuaString ls = s.strvalue(); if ( s.isnil() )
bytes = ls.m_bytes; return -1;
offset = ls.m_offset; LuaString ls = s.strvalue();
remaining = ls.m_length; bytes = ls.m_bytes;
if (remaining <= 0) offset = ls.m_offset;
return -1; remaining = ls.m_length;
} if (remaining <= 0)
--remaining; return -1;
return 0xFF&bytes[offset++]; }
} --remaining;
} return 0xFF&bytes[offset++];
} }
}
}