PageRenderTime 45ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/jEdit/tags/jedit-4-5-pre1/org/gjt/sp/jedit/bsh/commands/eval.bsh

#
Unknown | 75 lines | 65 code | 10 blank | 0 comment | 0 complexity | 0251c9dade841afedcc85f89d1ecc313 MD5 | raw file
Possible License(s): BSD-3-Clause, AGPL-1.0, Apache-2.0, LGPL-2.0, LGPL-3.0, GPL-2.0, CC-BY-SA-3.0, LGPL-2.1, GPL-3.0, MPL-2.0-no-copyleft-exception, IPL-1.0
  1. /**
  2. Evaluate the string in the current interpreter (see source()).
  3. Returns the result of the evaluation or null.
  4. <p>
  5. Evaluate a string as if it were written directly in the current scope,
  6. with side effects in the current scope.
  7. <p>
  8. e.g.
  9. <code><pre>
  10. a=5;
  11. eval("b=a*2");
  12. print(b); // 10
  13. </pre></code>
  14. <p>
  15. eval() acts just like invoked text except that any exceptions generated
  16. by the code are captured in a bsh.EvalError. This includes ParseException
  17. for syntactic errors and TargetError for exceptions thrown by the evaluated
  18. code.
  19. <p>
  20. e.g.
  21. <pre>
  22. try {
  23. eval("foo>>><>M>JK$LJLK$");
  24. } catch ( EvalError e ) {
  25. // ParseException caught here
  26. }
  27. try {
  28. eval("(Integer)true"); // illegal cast
  29. } catch ( EvalError e ) {
  30. // TargetException caught here
  31. print( e.getTarget() ) // prints ClassCastException
  32. }
  33. </pre>
  34. <p>
  35. If you want eval() to throw target exceptions directly, without wrapping
  36. them, you can simply redefine own eval like so:
  37. <pre>
  38. myEval( String expression ) {
  39. try {
  40. return eval( expression );
  41. } catch ( TargetError e ) {
  42. throw e.getTarget();
  43. }
  44. }
  45. </pre>
  46. <p/>
  47. Here is a cute example of how to use eval to implement a dynamic cast.
  48. i.e. to cast a script to an arbitrary type by name at run-time where the
  49. type is not known when you are writing the script. In this case the type
  50. is in the variable interfaceType.
  51. <pre>
  52. reference = eval( "("+interfaceType+")this" );
  53. </pre>
  54. <p>
  55. Returns the value of the expression.
  56. <p>
  57. Throws bsh.EvalError on error
  58. <p>
  59. @return the value of the expression.
  60. @throws bsh.EvalError on error
  61. */
  62. bsh.help.eval = "usage: eval( String expression )";
  63. Object eval( String expression ) {
  64. return this.interpreter.eval( expression, this.caller.namespace );
  65. }