Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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..

like image 875
Rakso Avatar asked Jul 28 '11 21:07

Rakso


1 Answers

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.

like image 150
Sébastien Le Callonnec Avatar answered Oct 20 '22 08:10

Sébastien Le Callonnec