环境搭建(Gradle)
- 下载最新的luaj源码。
- 把源码的core、jse里面的代码文件添加到你的项目里面,可能需要处理合并冲突。
- 添加bcel的引入,
build.gradle
如下。
group 'LuaJTest'
version '0.1-SNAPSHOT'
apply plugin: 'java'
sourceCompatibility = 1.8
repositories {
jcenter()
}
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.11'
//bcel for LuaJ
compile 'org.apache.bcel:bcel:5.2'
}
为什么使用源码而不是jar:源码能够进行debug,能够理解具体的逻辑,能够增加更多的功能。
增加read()
函数——Lua调用Java
read()
功能就是能够读取console里面的输入内容。
Java 示例功能说明。
private static String read() {
Scanner scanner = new Scanner(System.in);
return scanner.readLine();
}
具体实现
packagename/extend/BaseLib.java
package com.mislead.luaj.extend;
import java.util.Scanner;
import org.luaj.vm2.Globals;
import org.luaj.vm2.LuaString;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.lib.ZeroArgFunction;
/**
* BaseLib by Mislead on 2016/5/26.
*/
public class BaseLib {
private org.luaj.vm2.lib.BaseLib baseLib;
private Globals globals;
public BaseLib(org.luaj.vm2.lib.BaseLib baseLib, Globals globals) {
this.baseLib = baseLib;
this.globals = globals;
}
public void extend(LuaValue env) {
env.set("read", new read(baseLib));
}
// implements a read method to read the input line from console.
final class read extends ZeroArgFunction {
final org.luaj.vm2.lib.BaseLib baseLib;
public read(org.luaj.vm2.lib.BaseLib baseLib) {
this.baseLib = baseLib;
}
@Override public LuaValue call() {
Scanner scanner = new Scanner(System.in);
String result = scanner.nextLine();
return LuaString.valueOf(result);
}
}
}
注册功能
org.luaj.vm2.lib.BaseLib.java
// 需要把增加的功能添加到env
public LuaValue call(LuaValue modname, LuaValue env) {
... some codes
// to extend other methods
new com.mislead.luaj.extend.BaseLib(this, globals).extend(env);
next next;
env.set("next", next = new next());
env.set("pairs", new pairs(next));
env.set("ipairs", new ipairs());
return env;
}
使用示例read.lua
word = read()
print(word)