User
User

Reputation: 1488

change java variables from JRuby code?

As title says i whant to change my variables in java from my jruby code

To be more specific i have an integer in my Java code which has no value yet, And i whant with my JRuby code give this variable an value, But i have no idea how to do this.

This is how far i got with the JRuby code..

require 'java'
puts "Set player health here"
playerHealth = 3 # Setting player health here!

But have not yet wrote anything in java. This is pretty much all I have so far..

Upvotes: 6

Views: 737

Answers (1)

From what I understand, you are trying to invoke the JRuby engine from Java, so you could do something like this to modify a Java variable in JRuby:

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

Note that in the script playerHealth is a global variable.

Check out this link for more details if you want to load an external JRuby script rather than evaluating code.

Upvotes: 3

Related Questions