This is the expected behavior. You are getting an error when you call "fun2()" because of the earlier line which sets "fun2 = aValue". Before even running your code, you may notice that the line "fun2()" is underlined in orange. If you hover over this line, there is a warning message that says "The variable 'fun2' might be used before it is defined".
In a function, identifier names are statically resolved. Even though "fun2" is called out as a variable in a conditional branch which will never get executed during runtime, statically "fun2" gets classified as a variable. When you then call "fun2()" as a function in the else-block, "fun2" has already been classified as a variable. Because this variable has not yet been defined, you see the error message "Undefined function or variable".
If you executed the same conditional block in a script instead of inside a function, you would not receive the error message, because there would not be static name resolution. Similarly, this is why you can successfully run the line "fun2()" using F9 (evaluate expression) or from the command line. These are both runtime constructs, and so "fun2" is not statically classified as a variable.
The following are some potential workarounds:
1. Use different identifiers for the variable you define in the if-block, and the function you are calling in the else-block.
If you can avoid creating a variable with the same name as your function, this function will not get statically classified as a variable.
2. Use an "eval" command.
The "eval" command is a runtime construct, so it does not take into account the static name resolution from a function. You can use the "eval" command in the following manner:
For more details, please refer to the documentation for "eval":
Best Answer