-
cache
was implemented in core to support all the rules languages, not just JS Scripting -
The
cache
implements a registry that cleans these up automatically for you when the rule(s) that reference the value are unloaded, cancelling Timers and such. If you use a local variable and reload your rule, your Timer may still exist and when it runs it will generate an error. -
There is both a
private
cache and ashared
cache. Theshared
cache can be used to share variables between script actions and script conditions, not just preserve a variable from one run to the next in a single script action/condition. Note that the scripts that are sharing variables need not be written in the same language. -
In ECMAScript your cache example can be converted to
var counter = cache.private.get('counter', () => { times: 0 });
console.log('Count', counter.times++);
I prefer using the cache because it cleans up after itself automatically and has way more use cases than preserving a variable in a single script action or condition from one run to the next. It also has a cleaner syntax where you can pull the variable and initialize it if it’s not defined all on one line.