正如标题所说,我想从我的jruby代码中改变我的变量
更具体地说,我的Java代码中有一个整数,它没有任何值,而且我用我的JRuby代码给这个变量一个值,但我不知道怎么做。
这是我使用JRuby代码的程度。
require 'java'
puts "Set player health here"
playerHealth = 3 # Setting player health here!
但还没有在java中写过任何东西。到目前为止,这几乎就是我所有的......
答案 0 :(得分:2)
根据我的理解,您正在尝试从Java调用JRuby引擎,因此您可以执行类似这样的操作来修改JRuby中的Java变量:
import javax.script.*;
public class EvalJRubyScript {
public static void main(String[] args) throws Exception {
ScriptEngineManager factory = new ScriptEngineManager();
int playerHealth = 0;
ScriptEngine engine = factory.getEngineByName("jruby");
ScriptContext context = engine.getContext();
context.setAttribute("playerHealth", playerHealth, ScriptContext.ENGINE_SCOPE);
try {
engine.eval("$playerHealth = 42");
playerHealth = (Integer)context.getAttribute("playerHealth", ScriptContext.ENGINE_SCOPE);
System.out.println(playerHealth);
} catch (ScriptException exception) {
exception.printStackTrace();
}
}
}
请注意,脚本中playerHealth
是一个全局变量。
如果要加载外部JRuby脚本而不是评估代码,请查看this link以获取更多详细信息。