Using a String as an if-evaluation

edited October 2015 in Questions about Code

Hello,

I wonder if it is possible to use the content of a String as an evaluation request in an If-function.

I am very new to processing and am working on a longer code, the if requests gets generated by a for();

Happy for every help!

Thanks.

request = "(1 < 2) & (1 < 3)";

if (request) {
  println("ok");
}

Answers

  • You can't do this in Java mode. You'll need to parse the Strings yourself, or come up with a new design.

    You can do this with JavaScript through Processing.js, which is what Chrisir is mentioning.

  • edited October 2015

    If you are using Java Mode then you can use the Jasmine library but you would have to use the logical and/or (&& ||) instead of the bitwise and/or (& |).

    import org.quark.jasmine.*;
    
    String expr = "(1 < 2) && (1 < 3)";
    Expression e = Compile.expression(expr, false);
    boolean request = e.eval().answer().toBoolean();
    
    if (request) {
      println("That was true");
    } else {
      println("A falsehood!");
    }
    
  • edited October 2015
    /**
     * JS ScriptEngine Eval
     * GoToLoop (2015-Oct-29)
     *
     * forum.Processing.org/two/discussion/13311/using-a-string-as-an-if-evaluation
     * forum.Processing.org/two/discussion/316/processing-command-line
     *
     * JavaPapers.com/core-java/run-javascript-from-java/
     * www.IBM.com/developerworks/java/library/j-5things9/
     */
    
    import javax.script.ScriptEngine;
    import javax.script.ScriptEngineManager;
    import javax.script.ScriptException;
    
    final ScriptEngine js = new ScriptEngineManager().getEngineByName("javascript");
    
    static final String EXPRESSION_1 = "1<2 & 1<3";
    static final String EXPRESSION_2 = "1<2 && 1<3";
    
    String evaluation;
    boolean bool;
    
    void setup() {
      evaluation = eval(EXPRESSION_1, js);
      bool = boolean(int(evaluation));
      println('\"' + EXPRESSION_1 + '\"', '\t', evaluation, '\t', bool);
    
      evaluation = eval(EXPRESSION_2, js);
      bool = boolean(evaluation);
      println('\"' + EXPRESSION_2 + '\"', '\t', evaluation, '\t', bool);
    
      exit();
    }
    
    static final String eval(String expression, ScriptEngine engine) {
      try {
        return engine.eval(expression).toString();
      }
      catch (ScriptException ex) {
        throw new RuntimeException(ex);
      }
    }
    
  • That's cool. : - )

  • Also complete overkill for 90% of people with this question :p

Sign In or Register to comment.