What are chaiscript scoping rules? Question

0
I'm not sure if this is a problem or intended behavior but I'm pretty sure it's intended behavior. Initially I was thinking that a "try" block was different. Is the fact that "arl2" doesn't exist outside of the "try" block considered "intended behavior" or "defect"?

In the example below, the variable "arl1" is declared outside of the "try" context. It exists both outside and inside the "try". The variable "arl2" is declared inside the "try". It doesn't exist outside of the "try", so the line after the "try" referencing "arl2" errors.



------------ cut here ------------

// arl1 is declaired outside the "try" context
// arl2 is declaired inside the "try" block. It doesn't exist outside of that block.
var arl1 = Variant();

try {
LogInfoMsg("######## try ########" );
arl1 = Ext.CreateAppRecordList(Ext.TableId("TS_USERS","database")) ; // arl1 is a: chai:Variant / VBScript VarType:9 (Automation object) / Object / AppRecordList
var arl2 = Ext.CreateAppRecordList(Ext.TableId("TS_CONTACTS","database")) ; // arl2 is a: chai:AppRecordList
// do stuff that might cause exception
} catch(e) {
Ext.LogErrorMsg("FAILED: ${e.what()}") ;
}

// arl1 is a: chai:Variant / VBScript VarType:9 (Automation object) / Object / AppRecordList
LogInfoMsg("######## after ######## : arl1=${arl1}" );
// causes error : "Can not find object: arl2"
LogInfoMsg("######## after ######## : arl2=${arl2}" );

------------ cut here ------------

Accepted Answer

Monday, March 25 2019, 06:59 PM - #Permalink
0
Hi, Paul. Yes, the scoping rules are very similar to C++. As such, variables declared inside a try block go out of scope when that block ends (and are not available in a catch block or code following the try/catch. However, it is possible to declare the variable before the try, then define it inside the try block. You can test whether a variable is defined with a call to xxx.is_var_undef(). The term "declared" would be where you state "var xxx;", whereas "defined" would be the first place that the variable gets a value (and thus a type). The location the var is declared marks its scope.

Variables defined in the main scope (outside of a function) will not be visible inside a function unless declared as "global" rather than "var" (or unless you pass the var into the function). You can also define global variables inside a function, and after the script runs that function, that value will be available in all scopes after that point.

Finally, you can add global constants with a call to add_global_const. The value passed to this function must be constant and cannot be set from a runtime call (you cannot pass Ext.TableId("TS_USERS"), but you can pass the hard-coded 17). This value will be visible in all scopes, just like global variables, as soon as the script processes the call to add_global_const.
The reply is currently minimized Show
Responses (0)
  • There are no replies here yet.
Your Reply

Recent Tweets