4

Trying out the new library feature in a Google spreadsheet. I have include a library with the identifier of "Test" and the library implements the function "foo()"

entering =Test.foo() into a spreadsheet cell gives the error : "unknown function name TEST.FOO"

If I create a function in my spreadsheet to wrap the library function:

function foo()
{
  return Test.foo();
}

then use =foo() in my speadsheet cell, all is well. Creating wrapper functions for all library functions so they can be used in a spreadsheet cell makes using libraries less than ideal. Is there a way to call a library function from a spreadsheet cell?

Rubén
  • 34,714
  • 9
  • 70
  • 166
Hilo
  • 869
  • 2
  • 9
  • 24

2 Answers2

4

There's not currently a way to call these library functions directly as a custom function from a cell. Creating a wrapper, as you've done, is the way to do this currently. If you'd like to be able to call library functions directly as custom functions, please raise that as an issue on the Issue Tracker.

Jan Kleinert
  • 1,789
  • 9
  • 21
4

Here is a workaround that allows you to call any library function if you paste in this one generic wrapper function. Then you can call this from the spreadsheet.

For example, if I had a library called MyLib with a function add(x, y) (pretend x is in cell A1 and y is in cell A2) I could call it like this: =LIB_FUNC("MyLib", "add", A1, A2).

It's a little ugly but at least allows me to only have to paste this one function and then access any library function. Note that this depends on undocumented structure of the "this" object that is in scope when calling the wrapper function. Small chance this could break over time. Might see if I can publish this as an add on.

function LIB_FUNC(libraryName, functionName) {
  var result;
  var lib = this[libraryName];
  var extraArgs = [];

  if (lib) {
    var func = lib[functionName];

    if (func) {
      if (arguments.length > 2) {
        extraArgs = Array.apply(null, arguments).slice(2);
      }

      result = func.apply(this, extraArgs);
    } else {
      throw "No such function: " + functionName;
    }
  } else {
    throw "No such library: " + libraryName;
  }

  return result;
}
Joe Lynch
  • 41
  • 1