1

The following always shows 0 :

var gNumber = 0;

function myTest() {
  Browser.msgBox(gNumber);
  gNumber++;
}

I can, of course, use ScriptProperties or UserProperties to store a value permanently. Fine for simple values but it will not work for an object unless I stringify it. But with the latter, I cannot store permanently an object that opens a sheet and lets me manipulate it via methods (get, set).

I have an Orders spreadsheet that uses information from the Customers spreadsheet. Everytime I check an order, I need to open the Customers spreadsheet and load its data into an array. Is there a way to keep an object permanently so that I don't need to open Customers over and over again?

By permanently, I mean as long as the sheet associated with the script is open!

Is there a way I can do that?

Draken
  • 3,134
  • 13
  • 34
  • 54
ballatom
  • 43
  • 1
  • 1
  • 7

1 Answers1

6

If you need to store the variables for a temporary amount of time, use CacheService. If you want more persistent storage (similar to a spreadsheet), then you can make use of ScriptDb

Of course, ScriptProperties / UserProperties are also there for you to use, but I prefer CacheService over ScriptProperties because you can hit the limit on ScriptProperties pretty quickly.

Srik
  • 7,907
  • 2
  • 20
  • 29
  • Yes, the CacheService seems to partially cover my needs. I will try it with objects and see if it works for my particular case. Thx. – ballatom Dec 26 '12 at 11:49
  • "Global" variables in GAS are constants if they're assigned as you've shown above. If they're only declared, but not defined in the global scope, then they will take whatever value you set in methods and be available to all methods in one execution of the script. Any longer-term storage needs one of the ways Srik mentioned. – Fred Dec 26 '12 at 12:56
  • Your spreadsheet example is a 'special case' : you can get the data array as a global variable and it will be indeed available to all other functions. If you need to change some data in the array just do it and write back the array to the SS so that the change won't be lost(that makes it easily 'persistent') have a quick peek at [this code](https://script.google.com/d/1aL_y6ZqrfqrzhDZ4yzxM9Ax5hGi9KOHR0ltZ-7gVOTpQCDXV9zY3Ka_Y/edit) where I get an array called 'data' and use it all along throughout the script. – Serge insas Dec 26 '12 at 16:05