theworldismyoyster
theworldismyoyster

Reputation: 569

google script how to call library functions dynamically?

I have a set of libraries that have the same functions in each (each library is associated with a template and every time different templates can be used, depending on the user request). I am trying to create a code that will call functions dynamically. This is fine as long as the functions are in the same script. However, my functions are in different libraries and when I try to call them I get an error: Execution failed: TypeError: Cannot find function Script2.returnWord in object [object Object]. (line 25, file "dynamicFunctionsTest").

Here is the code:

function test1() { 
  return 'raining';
}

function test2() {
  return 'cats';
}

function test3() { 
  return ScriptLibrary1.returnWord();   // the function returns the word 'and'
}

function testing() {

  var message;
  var func = [];
  func [0] = 'test1';
  func [1] = 'test2';
  func [2] = 'test3';
  func [3] = 'ScriptLibrary2.returnWord';  // the function returns the word 'dogs'

  Browser.msgBox(func);  // check values before calling

  for (var i = 0; i < func.length ; ++i) {    
    message = this[func[i]]();               // this line fails on the 4th one
    Browser.msgBox(message);
  }  
}

I am getting the first 3 working (the third was just a test to see if I can call locally which works but is insufficient for my purpose), but it fails on the 4th one.

Anyone has any idea how to get it to work?

Thanks. PS. The script is called from a google spreadsheet.

Upvotes: 0

Views: 701

Answers (3)

Tim
Tim

Reputation: 766

I agree with Zig, could you explain why you need separate libraries?

Normally you would do this because of logical groupings (email functions/maths functions/application-specific functions etc), certainly you would not repeat functions across libraries. It's like addins in Excel, you don't have Maths functions spread around different addins, you have 1 set of Maths functions in 1 library and you always access that lib when you want them.

Upvotes: 0

Zig Mandel
Zig Mandel

Reputation: 19835

This is not how libraries are used. Put everything on a single lib and have an extra param that tells it which one to call.

Upvotes: 1

wchiquito
wchiquito

Reputation: 16551

One option may be to use eval(), but remember you have to be careful with this function.

...
message = eval(func[i])();
...

Another option may be:

...
var myFunc;
...
myFunc = new Function('return ' + func[i]);
message = myFunc()();
...

Upvotes: 1

Related Questions