Script Shell (GE) fails for the simplest if-else clause

Related to a script code in this topic

This most simple if-else clause fails for GE but not as script file using ‘Run Script’ (XC):

var document = EAction.getDocument();

if (!isNull(document) && document.hasSelection()) {
    // Do something meaningful:
    EAction.handleUserInfo("Done something meaningful.");
}
else {
    // Warn user on critical faults:
    EAction.handleUserWarning("No document or no selection.");
}

A command string is concatenated until the count of all open brackets ( & { & [ equals the count of all closing brackets ) & } & ].
The above code is thus evaluated in 3 steps:

  • eval(“var document = EAction.getDocument();”)
  • eval(“if (…) {…}”)
  • eval(“else {…}”) Resulting in a: Syntax error
    In what other condition would else apply if evaluated apart from the if clause?

The code below doesn’t fail:

var document = EAction.getDocument();

if (1 > 0) {
    if (!isNull(document) && document.hasSelection()) {
        // Do something meaningful:
        EAction.handleUserInfo("Done something meaningful.");
    }
    else {
        // Warn user on critical faults:
        EAction.handleUserWarning("No document or no selection.");
    }
}

Evaluated in two steps:

  • eval(“var document = EAction.getDocument();”)
  • eval(“if (1>0) {…}”)

The “if (1 > 0) {…}” fix does work when enclosing the specific 71 lines of code in the related topic.
But you can’t stretch it indefinitely.


:arrow_right: Also remark that brackets in plain text or comments are accounted for just the same. :unamused:

// This won't run because of the Sad smiley :( 
var document = EAction.getDocument();

if (!isNull(document) && document.hasSelection()) {
    // Do something meaningful:
    EAction.handleUserInfo("Done something meaningful.");
}
else {
    // Warn user on critical faults:
    EAction.handleUserWarning("No document or no selection.");
}

Not evaluated yet, the Shell expect more lines including one with the associated closing bracket of the smiley.
Add that bracket in a comment otherwise it results in a: Syntax error

Include brackets in plain text intended for a string using their character codes.


Another solution is to include your code as a block starting with ‘{’ and ending with ‘}’
And yet another solution but much slower is defining the block as a function and calling this function.

function main() {
    ....
};

main();

The last 2 solutions rely on the fact that the block text or the function text is only evaluated after the last closing bracket.
Just the same as with the dummy “if (1>0) {…}” clause.

Regards,
CVH