Jscript global var confusion

Please take a look at the code below: the "counter" variable is defined in global scope (which is probably incorrect for Opus scripting?) so in OnListItem it increases, but if I try to access it from OnBeforeFolderChange, I always get the default value of 0 and if I try to set it to some value it never changes as far as the OnListItem is concerned. So effectively I can't reset the "counter" var to zero upon each lister refresh.

The unwanted result when running this script is that "counter" var gets ever-increased between lister refreshes (F5) instead of being reset to 0 by OnBeforeFolderChange.

It acts as if each function gets its own "counter" var copy instead of sharing the same one.

[code]var counter = 0;

function OnInit(initData)
{
initData.name = "Scripting Column lister refresh-trouble test";
initData.desc = "Minimal test script, turn the column on and refresh the lister multiple times.";
initData.copyright = "";
initData.version = "0.0.0";
initData.default_enable = true;
initData.min_version = "11.5.2";

var col = initData.AddColumn();
col.name = "Test column"
col.label = "Test column"
col.method = "OnListItem";
col.justify = "left";
col.multicol = false;

}

function OnBeforeFolderChange(BeforeFolderChangeData )
{
counter = 0;
}

function OnListItem(scriptColData)
{
counter += 1;
scriptColData.value = scriptColData.col + counter;
}[/code]

It's better to use tab-scoped and DO "internal" variables here it seems.

What you see is explainable if you know:

  • a call to OnBeforeFolderChange() will always run the script "fresh" from top to bottom, just skipping the OnInit() function.
  • OnListItem() on the other hand, and since it is a column callback, will not always run the script from top to bottom.
    That will only happen, if the calls to OnListItem() are paused by some seconds. The script context will stay for continued calls to OnListItem(), this is a performance feature I guess. In a filedisplay with thousends of items, it would be overkill to execute the whole script again and again, so DO is clever and keeps the script thread/context to only call OnListItem() repeatedly on each item.

That's way you see counter is 0 on each call to OnBeforeFolderChange() and why counter will increase for OnListItem() in specific situations.
Make the test, wait 20 seconds or so, then refresh the lister, your column will reveal that counter will start from zero again, because the script thread died in the meantime.

As said in the beginning, you can fix all this by sticking to DO internal variables. Tab scoped once seem to be appropriate here, but script scoped can also be used I think, need specific handling when saving and looking up (path specific), to avoid a global script scoped counter, unless that's what you are aiming at.

Thank you tbone for this helpful and in-depth answer! Your high quality contributions to this community should definitely be rewarded! :thumbsup: