Clarification on variable default values

I’ve updated my notes on the var operator for variables: var.

Most variables, except Number, Date and Boolean types are actually based off string so the issue I’m updating for is moot. But—and since discovery (as at v9.6.1) this will likely be updated—declaring a typed variable, e.g. a Number-type, does not set a default value. Thus:

var:string vString; // value is ""
//but
var:number vNum; // value is "". Really?

Yes, so especially when using a Number-type, seeing a default value is a good idea, i.e

var:number vNum 0 ; // value is 0

This matters if using a user-set counter when an iterating a loop:

var:number vCounter;
$AList = collect(children,$Name);
$SomeList.each(anItem){
   $Text(/log) = $AList[vCounter];
   vCounter+=1;
};

For the first run of the loop, vCounter is "" so $AList[vCounter] returns … nothing. The counter setting code at the looop end adds 1. So, on loop #2, the value fetched is $AList[1] and the result is as expected.

As noted, this will likely be resolved in future version so that using an explicit var:type declaration will both set the type and that type’s default. IOW, var:number vCounter; would then set vCounter as 0`. But, as at v9.5.1 this isn’t so.

Other data types are less likely to be problematic in the interim. But, until then if using Number type variables, it is a good idea to explicitly set the type default of 0 (zero), i.e.:

var:number vCounter = 0;

Suffice it to say I tripped up on this recently and spent a lot of time chasing the wrong causes until the penny dropped as to the real cause.

1 Like

The ought to me

var:number vNum=0;

or

var:number vNum(0);

Note that the following does appear to function correctly:

var:number n;
n+=1;
$MyNumber=n;

I notice that in the loop, there’s a typo vConter+=1; .

1 Like

Typo above in (my last post) fixed!

But, and the point of the update:

var:number n;
$MyNumber=n;

leaves $MyNumber undefined. IOW it inherits the document’s default of $MyNumber (i.e. 0) but it is not _set_ via the action above as that applies a value of “”` which $MyNumber cannot hold.

Sorry, I should add that this isn’t a existential horror for most users: I’m not throwing shade at Eastgate. But for those iterating numerical counters it might save hours of running down the wrong source of error—if you assume declaring a Number-type variable without a value has a value of 1.

$MyNumber=42; 
var:number n;
$MyNumber=n;

I believe that the value of $MyNumber after this rule runs is 0. Is that not what you see? (I’m trying to write a test case to identify the problem.)

Presumably due to auto-coercion. But if I run:

$MyNumber=42; 
var:number n;
$Text=n;

The result is nothing:

Untitled 2023-08-28 22-19-11