Java源码示例:org.luaj.vm2.LuaTable
示例1
/**
* 使用Lua脚本与JStarCraft框架交互
*
* <pre>
* Java 11执行单元测试会抛<b>Unable to make {member} accessible: module {A} does not '{operation} {package}' to {B}</b>异常
* 是由于Java 9模块化导致
* 需要使用JVM参数:--add-exports java.base/jdk.internal.loader=ALL-UNNAMED
* </pre>
*
* @throws Exception
*/
@Test
public void testLua() throws Exception {
// 获取Lua脚本
File file = new File(ScriptTestCase.class.getResource("Model.lua").toURI());
String script = FileUtils.readFileToString(file, StringUtility.CHARSET);
// 设置Lua脚本使用到的Java类
ScriptContext context = new ScriptContext();
context.useClasses(Properties.class, Assert.class);
context.useClass("Configurator", MapConfigurator.class);
context.useClasses("com.jstarcraft.ai.evaluate");
context.useClasses("com.jstarcraft.rns.task");
context.useClasses("com.jstarcraft.rns.model.benchmark");
// 设置Lua脚本使用到的Java变量
ScriptScope scope = new ScriptScope();
scope.createAttribute("loader", loader);
// 执行Lua脚本
ScriptExpression expression = new LuaExpression(context, scope, script);
LuaTable data = expression.doWith(LuaTable.class);
Assert.assertEquals(0.005825241F, data.get("precision").tofloat(), 0F);
Assert.assertEquals(0.011579763F, data.get("recall").tofloat(), 0F);
Assert.assertEquals(1.2708743F, data.get("mae").tofloat(), 0F);
Assert.assertEquals(2.425075F, data.get("mse").tofloat(), 0F);
}
示例2
public LuaValue call(LuaValue modname, LuaValue env) {
globals = env.checkglobals();
globals.set("require", new require());
package_ = new LuaTable();
package_.set(_LOADED, new LuaTable());
package_.set(_PRELOAD, new LuaTable());
package_.set(_PATH, LuaValue.valueOf(DEFAULT_LUA_PATH));
package_.set(_LOADLIB, new loadlib());
package_.set(_SEARCHPATH, new searchpath());
LuaTable searchers = new LuaTable();
searchers.set(1, preload_searcher = new preload_searcher());
searchers.set(2, lua_searcher = new lua_searcher());
searchers.set(3, java_searcher = new java_searcher());
package_.set(_SEARCHERS, searchers);
package_.get(_LOADED).set("package", package_);
env.set("package", package_);
globals.package_ = this;
return env;
}
示例3
/**
* bind lua functions using opcode
*
* @param factory
* @param methods
* @return
*/
public static LuaTable bind(Class<? extends LibFunction> factory, List<String> methods) {
LuaTable env = new LuaTable();
try {
if (methods != null) {
for (int i = 0; i < methods.size(); i++) {
LibFunction f = factory.newInstance();
f.opcode = i;
f.method = null;
f.name = methods.get(i);
env.set(f.name, f);
}
}
} catch (Exception e) {
throw new LuaError("[Bind Failed] " + e);
} finally {
return env;
}
}
示例4
/**
* create metatable for libs
*
* @return
*/
public static LuaTable createMetatable(Class<? extends LibFunction> libClass) {
LuaTable result = AppCache.getCache(AppCache.CACHE_METATABLES).get(libClass);//get from cache
if (result == null) {
LuaTable libTable = null;
if (LuaViewConfig.isUseNoReflection()) {
List<String> methodNames = getMapperMethodNames(libClass);
libTable = LuaViewManager.bind(libClass, methodNames);
} else {
List<Method> methods = getMapperMethods(libClass);
libTable = LuaViewManager.bindMethods(libClass, methods);
}
result = LuaValue.tableOf(new LuaValue[]{LuaValue.INDEX, libTable, LuaValue.NEWINDEX, new NewIndexFunction(libTable)});
//update cache
AppCache.getCache(AppCache.CACHE_METATABLES).put(libClass, result);
}
return result;
}
示例5
/**
* 开始帧动画
*
* @param view
* @param varargs 时间是秒而不是毫秒
* @return
*/
@Deprecated
public LuaValue startAnimationImages(U view, Varargs varargs) {//TODO 支持UDImageView和UDBitmap
final LuaTable imagesTable = varargs.opttable(2, null);
final double duration = varargs.optdouble(3, 1f);
boolean repeat = false;
if (varargs.isnumber(4)) {
repeat = varargs.optint(4, -1) > 0;
} else {
repeat = varargs.optboolean(4, false);
}
if (imagesTable != null && imagesTable.length() > 0) {
final String[] images = new String[imagesTable.length()];
int i = 0;
for (LuaValue key : imagesTable.keys()) {
images[i++] = imagesTable.get(key).optjstring(null);
}
return view.startAnimationImages(images, (int) duration * 1000, repeat);
}
return view;
}
示例6
public LuaValue call(LuaValue modname, LuaValue env) {
globals = env.checkglobals();
// io lib functions
LuaTable t = new LuaTable();
bind(t, IoLibV.class, IO_NAMES );
// create file methods table
filemethods = new LuaTable();
bind(filemethods, IoLibV.class, FILE_NAMES, FILE_CLOSE );
// set up file metatable
LuaTable mt = new LuaTable();
bind(mt, IoLibV.class, new String[] { "__index" }, IO_INDEX );
t.setmetatable( mt );
// all functions link to library instance
setLibInstance( t );
setLibInstance( filemethods );
setLibInstance( mt );
// return the table
env.set("io", t);
env.get("package").get("loaded").set("io", t);
return t;
}
示例7
/**
* get value of given type, from varargs of key [poslist]
*
* @param type
* @param varargs
* @param keylist
* @return
*/
static Object getValueFromTable(int type, Varargs varargs, Object defaultValue, String... keylist) {
Object result = null;
if (varargs instanceof LuaTable) {
LuaTable varlist = ((LuaTable) varargs);
if (keylist != null && keylist.length > 0) {
for (int i = 0; i < keylist.length; i++) {
result = parseValue(type, varlist.get(keylist[i]));
if (result != null) {
break;
}
}
}
}
return result != null ? result : defaultValue;
}
示例8
@Override
public LuaValue invoke(Varargs args) {
int fixIndex = VenvyLVLibBinder.fixIndex(args);
if (args.narg() > fixIndex) {
LuaTable table = LuaUtil.getTable(args, fixIndex + 1);
Map<String, String> map = LuaUtil.toMap(table);
if (map == null || map.size() <= 0) {
return LuaValue.NIL;
}
String[] preLoadUrls = new String[map.size()];
for (Map.Entry<String, String> entry : map.entrySet()) {
preLoadUrls[Integer.valueOf(entry.getKey()) - 1] = entry.getValue();
}
mPlatform.preloadImage(preLoadUrls, null);
}
return LuaValue.NIL;
}
示例9
@Override
public LuaValue invoke(Varargs args) {
int fixIndex = VenvyLVLibBinder.fixIndex(args);
if (args.narg() > fixIndex) {
LuaTable table = LuaUtil.getTable(args, fixIndex + 1);
Map<String, String> map = LuaUtil.toMap(table);
if (map == null || map.size() <= 0) {
return LuaValue.NIL;
}
String[] preLoadUrls = new String[map.size()];
for (Map.Entry<String, String> entry : map.entrySet()) {
preLoadUrls[Integer.valueOf(entry.getKey()) - 1] = entry.getValue();
}
mPlatform.preloadMedia(preLoadUrls, null);
}
return LuaValue.NIL;
}
示例10
public Varargs invoke(Varargs args) {
switch (args.narg()) {
case 0: case 1: {
return argerror(2, "value expected");
}
case 2: {
LuaTable table = args.arg1().checktable();
table.insert(table.length()+1,args.arg(2));
return NONE;
}
default: {
args.arg1().checktable().insert(args.checkint(2),args.arg(3));
return NONE;
}
}
}
示例11
@Override
public Varargs invoke(Varargs args) {
int fixIndex = VenvyLVLibBinder.fixIndex(args);
LuaValue luaKey = args.arg(fixIndex + 1);
String key = luaValueToString(luaKey);
SharedPreferences spf = App.getContext().getSharedPreferences(cacheFileName, Activity.MODE_PRIVATE);
final Map<String, ?> spfValues = spf.getAll();
if (spfValues == null) {
return null;
}
LuaTable table = new LuaTable();
Set<String> keys = spfValues.keySet();
for (String s : keys) {
//包含指定key
if (s.contains(key)) {
String value = (String) spfValues.get(s);
if (value == null) {
value = "";
}
table.set(LuaValue.valueOf(s), LuaValue.valueOf(value));
}
}
return table;
}
示例12
/** Perform one-time initialization on the library by adding package functions
* to the supplied environment, and returning it as the return value.
* It also creates the package.preload and package.loaded tables for use by
* other libraries.
* @param modname the module name supplied if this is loaded via 'require'.
* @param env the environment to load into, typically a Globals instance.
*/
public LuaValue call(LuaValue modname, LuaValue env) {
globals = env.checkglobals();
globals.set("require", new require());
package_ = new LuaTable();
package_.set(_LOADED, new LuaTable());
package_.set(_PRELOAD, new LuaTable());
package_.set(_PATH, LuaValue.valueOf(DEFAULT_LUA_PATH));
package_.set(_LOADLIB, new loadlib());
package_.set(_SEARCHPATH, new searchpath());
LuaTable searchers = new LuaTable();
searchers.set(1, preload_searcher = new preload_searcher());
searchers.set(2, lua_searcher = new lua_searcher());
searchers.set(3, java_searcher = new java_searcher());
package_.set(_SEARCHERS, searchers);
package_.set("config", FILE_SEP + "\n;\n?\n!\n-\n");
package_.get(_LOADED).set("package", package_);
env.set("package", package_);
globals.package_ = this;
return env;
}
示例13
public static LuaValue complexToLua(Object o) {
try {
Class<?> c = o.getClass();
Field[] fields = c.getFields();
LuaTable table = new LuaTable();
for (Field field : fields) {
if (!(Modifier.isPublic(field.getModifiers()) || field.isAnnotationPresent(LuaInclude.class)) || field.isAnnotationPresent(LuaExclude.class))
continue;
String name = field.getName();
Object instance = field.get(o);
LuaValue l = convertToLua(instance);
table.set(name, l);
}
return table;
} catch (Exception e) {
Log.warning(e);
}
return NIL;
}
示例14
@Override
public Varargs invoke(Varargs args) {
int fixIndex = VenvyLVLibBinder.fixIndex(args);
Integer type = LuaUtil.getInt(args, fixIndex + 1);//事件类型
LuaTable table = LuaUtil.getTable(args, fixIndex + 2);
if(type == null || table == null){
return LuaValue.NIL;
}
HashMap<String, String> miniAppMap = LuaUtil.toMap(table);
if (miniAppMap == null) {
return LuaValue.NIL;
}
JSONObject dataObj = new JSONObject(miniAppMap);
if(dataObj != null){
VenvyStatisticsManager.getInstance().submitCommonTrack(type,dataObj);
}
return LuaValue.NIL;
}
示例15
@Override
public Varargs invoke(Varargs args) {
if (mPlatform == null || mPlatform.getPlatformLoginInterface() == null) {
return LuaValue.NIL;
}
final int fixIndex = VenvyLVLibBinder.fixIndex(args);
if (args.narg() > fixIndex) {
LuaTable table = LuaUtil.getTable(args, fixIndex + 1);
if (table.isnil()) {
return LuaValue.NIL;
}
Object object = JsonUtil.toJSON(table);
if (object != null && object instanceof JSONObject) {
mPlatform.getPlatformLoginInterface().userLogined(new PlatformUserInfo((JSONObject) object));
}
}
return LuaValue.NIL;
}
示例16
public static LuaTable mapping(Class<?> c) {
try {
LuaTable luaTable = new LuaTable();
for (Field field : c.getFields()) {
if (!Modifier.isStatic(field.getModifiers())) continue;
if (LuaValue.class.isAssignableFrom(field.getType())) {
luaTable.set(field.getName(), (LuaValue) field.get(null));
}
if (field.getType().equals(Class.class)) {
luaTable.set(field.getName(), mapping((Class<?>) field.get(null)));
}
}
return new ReadOnlyLuaTable(luaTable);
} catch (Exception e) {
throw new CubesException("Failed to create lua api", e);
}
}
示例17
public static void complexToJava(LuaValue l, Object o) {
try {
Field[] fields = o.getClass().getFields();
LuaTable table = l.checktable();
for (Field field : fields) {
if (!(Modifier.isPublic(field.getModifiers()) || field.isAnnotationPresent(LuaInclude.class)) || field.isAnnotationPresent(LuaExclude.class))
continue;
if (Modifier.isFinal(field.getModifiers())) continue;
String name = field.getName();
Class<?> type = field.getType();
LuaValue v = table.get(name);
Object instance = convertToJava(type, v);
field.set(o, instance);
}
} catch (Exception e) {
Log.warning(e);
}
}
示例18
private LuaValue startConnect(Varargs args, LVHttpBridge lvHttpBridge, RequestType requestType) {
final int fixIndex = VenvyLVLibBinder.fixIndex(args);
int requestId = -1;
if (args.narg() > fixIndex) {
String url = LuaUtil.getString(args, 2);
LuaTable table = LuaUtil.getTable(args, 3);
LuaFunction callback = LuaUtil.getFunction(args, 4);
switch (requestType) {
case GET:
requestId = lvHttpBridge.get(url, table, callback);
break;
case POST:
requestId = lvHttpBridge.post(url, table, callback);
break;
case PUT:
requestId = lvHttpBridge.put(url, table, callback);
break;
case DELETE:
requestId = lvHttpBridge.delete(url, table, callback);
break;
}
}
return LuaValue.valueOf(requestId);
}
示例19
public CustomSpell(String scriptFile) {
this.scriptFile = scriptFile;
script = new LuaScript("scripts/spells/" + scriptFile, this);
LuaTable desc = script.run("spellDesc").checktable();
image = desc.rawget("image").checkint();
imageFile = desc.rawget("imageFile").checkjstring();
name = StringsManager.maybeId(desc.rawget("name").checkjstring());
info = StringsManager.maybeId(desc.rawget("info").checkjstring());
magicAffinity = StringsManager.maybeId(desc.rawget("magicAffinity").checkjstring());
targetingType = desc.rawget("targetingType").checkjstring();
cooldown = (float) desc.rawget("cooldown").checkdouble();
level = (int) desc.rawget("level").checkdouble();
spellCost = (int) desc.rawget("spellCost").checkdouble();
castTime = (float) desc.rawget("castTime").checkdouble();
}
示例20
public LuaValue startMqtt(U target, Varargs args) {
try {
if (args.narg() > 0) {
LuaTable table = LuaUtil.getTable(args, 2);
LuaTable configTable = LuaUtil.getTable(args, 3);
Map<String, String> topsMap = LuaUtil.toMap(table);
if (topsMap != null && configTable != null) {
SocketUserInfo info = new SocketUserInfo(configTable.get("username").tojstring(), configTable.get("password").tojstring(), configTable.get("host").tojstring(), configTable.get("port").tojstring(), configTable.get("clientId").tojstring());
target.setMqttTopics(info, topsMap);
}
}
} catch (Exception e) {
VenvyLog.e(VenvyMqttMapper.class.getName(), e);
}
return LuaValue.NIL;
}
示例21
public LuaValue call(LuaValue modname, LuaValue env) {
globals = env.checkglobals();
// io lib functions
LuaTable t = new LuaTable();
bind(t, IoLibV.class, IO_NAMES );
// create file methods table
filemethods = new LuaTable();
bind(filemethods, IoLibV.class, FILE_NAMES, FILE_CLOSE );
// set up file metatable
LuaTable mt = new LuaTable();
bind(mt, IoLibV.class, new String[] { "__index" }, IO_INDEX );
t.setmetatable( mt );
// all functions link to library instance
setLibInstance( t );
setLibInstance( filemethods );
setLibInstance( mt );
// return the table
env.set("io", t);
env.get("package").get("loaded").set("io", t);
return t;
}
示例22
/** Perform one-time initialization on the library by adding package functions
* to the supplied environment, and returning it as the return value.
* It also creates the package.preload and package.loaded tables for use by
* other libraries.
* @param modname the module name supplied if this is loaded via 'require'.
* @param env the environment to load into, typically a Globals instance.
*/
public LuaValue call(LuaValue modname, LuaValue env) {
globals = env.checkglobals();
globals.set("require", new require());
package_ = new LuaTable();
package_.set(_LOADED, new LuaTable());
package_.set(_PRELOAD, new LuaTable());
package_.set(_PATH, LuaValue.valueOf(DEFAULT_LUA_PATH));
package_.set(_LOADLIB, new loadlib());
package_.set(_SEARCHPATH, new searchpath());
LuaTable searchers = new LuaTable();
searchers.set(1, preload_searcher = new preload_searcher());
searchers.set(2, lua_searcher = new lua_searcher());
searchers.set(3, java_searcher = new java_searcher());
package_.set(_SEARCHERS, searchers);
package_.get(_LOADED).set("package", package_);
env.set("package", package_);
globals.package_ = this;
return env;
}
示例23
public Varargs invoke(Varargs args) {
switch (args.narg()) {
case 0: case 1: {
return argerror(2, "value expected");
}
case 2: {
LuaTable table = args.arg1().checktable();
table.insert(table.length()+1,args.arg(2));
return NONE;
}
default: {
args.arg1().checktable().insert(args.checkint(2),args.arg(3));
return NONE;
}
}
}
示例24
/** Perform one-time initialization on the library by creating a table
* containing the library functions, adding that table to the supplied environment,
* adding the table to package.loaded, and returning table as the return value.
* Creates a metatable that uses __INDEX to fall back on itself to support string
* method operations.
* If the shared strings metatable instance is null, will set the metatable as
* the global shared metatable for strings.
* <P>
* 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.
*/
public LuaValue call(LuaValue modname, LuaValue env) {
LuaTable string = new LuaTable();
string.set("byte", new byte_());
string.set("char", new char_());
string.set("dump", new dump());
string.set("find", new find());
string.set("format", new format());
string.set("gmatch", new gmatch());
string.set("gsub", new gsub());
string.set("len", new len());
string.set("lower", new lower());
string.set("match", new match());
string.set("rep", new rep());
string.set("reverse", new reverse());
string.set("sub", new sub());
string.set("upper", new upper());
LuaTable mt = LuaValue.tableOf(
new LuaValue[] { INDEX, string });
env.set("string", string);
env.get("package").get("loaded").set("string", string);
if (LuaString.s_metatable == null)
LuaString.s_metatable = mt;
return string;
}
示例25
private LuaTable getTableFromElement(JsonElement element) {
LuaTable finalTable = new LuaTable();
if (element.isJsonArray()) {
JsonArray array = element.getAsJsonArray();
for (int i = 0; i < array.size(); i++) {
// Add one to i to match Lua array indexing standards
finalTable.set(i + 1, this.getValueFromElement(array.get(i)));
}
} else {
JsonObject obj = element.getAsJsonObject();
for (Map.Entry<String, JsonElement> objectEntry : obj.entrySet()) {
finalTable.set(objectEntry.getKey(), this.getValueFromElement(objectEntry.getValue()));
}
}
return finalTable;
}
示例26
public static LuaTable mapping(Object o) {
try {
LuaTable luaTable = new LuaTable();
for (Field field : o.getClass().getFields()) {
if (Modifier.isStatic(field.getModifiers())) continue;
if (LuaValue.class.isAssignableFrom(field.getType())) {
luaTable.set(field.getName(), (LuaValue) field.get(o));
}
if (field.getType().equals(Class.class)) {
luaTable.set(field.getName(), mapping((Class<?>) field.get(o)));
}
}
return new ReadOnlyLuaTable(luaTable);
} catch (Exception e) {
throw new CubesException("Failed to create lua api", e);
}
}
示例27
/** Perform one-time initialization on the library by creating a table
* containing the library functions, adding that table to the supplied environment,
* adding the table to package.loaded, and returning table as the return value.
* @param modname the module name supplied if this is loaded via 'require'.
* @param env the environment to load into, which must be a Globals instance.
*/
public LuaValue call(LuaValue modname, LuaValue env) {
globals = env.checkglobals();
globals.debuglib = this;
LuaTable debug = new LuaTable();
debug.set("debug", new debug());
debug.set("gethook", new gethook());
debug.set("getinfo", new getinfo());
debug.set("getlocal", new getlocal());
debug.set("getmetatable", new getmetatable());
debug.set("getregistry", new getregistry());
debug.set("getupvalue", new getupvalue());
debug.set("getuservalue", new getuservalue());
debug.set("sethook", new sethook());
debug.set("setlocal", new setlocal());
debug.set("setmetatable", new setmetatable());
debug.set("setupvalue", new setupvalue());
debug.set("setuservalue", new setuservalue());
debug.set("traceback", new traceback());
debug.set("upvalueid", new upvalueid());
debug.set("upvaluejoin", new upvaluejoin());
env.set("debug", debug);
env.get("package").get("loaded").set("debug", debug);
return debug;
}
示例28
/** Perform one-time initialization on the library by creating a table
* containing the library functions, adding that table to the supplied environment,
* adding the table to package.loaded, and returning table as the return value.
* Creates a metatable that uses __INDEX to fall back on itself to support string
* method operations.
* If the shared strings metatable instance is null, will set the metatable as
* the global shared metatable for strings.
* <P>
* 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.
*/
public LuaValue call(LuaValue modname, LuaValue env) {
LuaTable string = new LuaTable();
string.set("byte", new byte_());
string.set("char", new char_());
string.set("dump", new dump());
string.set("find", new find());
string.set("format", new format());
string.set("gmatch", new gmatch());
string.set("gsub", new gsub());
string.set("len", new len());
string.set("lower", new lower());
string.set("match", new match());
string.set("rep", new rep());
string.set("reverse", new reverse());
string.set("sub", new sub());
string.set("upper", new upper());
LuaTable mt = LuaValue.tableOf(
new LuaValue[] { INDEX, string });
env.set("string", string);
env.get("package").get("loaded").set("string", string);
if (LuaString.s_metatable == null)
LuaString.s_metatable = mt;
return string;
}
示例29
public LuaValue call(LuaValue modname, LuaValue env) {
globals = env.checkglobals();
LuaTable os = new LuaTable();
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);
return os;
}
示例30
public LuaValue call(LuaValue modname, LuaValue env) {
globals = env.checkglobals();
globals.debuglib = this;
LuaTable debug = new LuaTable();
debug.set("debug", new debug());
debug.set("gethook", new gethook());
debug.set("getinfo", new getinfo());
debug.set("getlocal", new getlocal());
debug.set("getmetatable", new getmetatable());
debug.set("getregistry", new getregistry());
debug.set("getupvalue", new getupvalue());
debug.set("getuservalue", new getuservalue());
debug.set("sethook", new sethook());
debug.set("setlocal", new setlocal());
debug.set("setmetatable", new setmetatable());
debug.set("setupvalue", new setupvalue());
debug.set("setuservalue", new setuservalue());
debug.set("traceback", new traceback());
debug.set("upvalueid", new upvalueid());
debug.set("upvaluejoin", new upvaluejoin());
debug.set("traceback_count", new tracebackCount());
//extend for luaview remove by yanqiu
// new com.taobao.luaview.vm.extend.DebugLib(this,globals).extend(debug);
env.set("debug", debug);
env.get("package").get("loaded").set("debug", debug);
return debug;
}