6

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

3
  • 1
    Check this out. kenai.com/projects/jruby/pages/CallingJavaFromJRuby. For example >> java.lang.System.setProperty "myprop", "123" => nil >> java.lang.System.getProperty "myprop" java.lang.System.getProperty "myprop" => "123" Commented Jul 29, 2011 at 0:47
  • Do you plan to call java from jruby, or call jruby from java? Also, why have different components messing with eachothers variables? That's probably not a good idea even within a single language. Why not set your variable with the return value from a method call? Commented Aug 9, 2011 at 7:46
  • I don't know how to do that either.. Commented Aug 9, 2011 at 11:33

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.