joey hendrickson
joey hendrickson

Reputation: 19

Google script function returns null even though variable contains data

I have a small problem with a program I am trying to create. It is supposed to figure out how much exp it would take to bring an ability to a certain level. I have not yet gotten that far, as I am having trouble with the return at the end of the CalculateCost function. I was trying to pass an array of strings back to the function which called CalculateCost, however, this wasn't working, so I tried to join all the values into a single string. This also didn't work. I know that the variable that I am trying to return is not null, as I am using ui.alert() quite frequently to check variables' values. Any help would be greatly appreciated. Here is the google sheet in question. https://docs.google.com/spreadsheets/d/1Xo_uppFDI_C65EVi-TZ1iHTseK-Fg1izyCRkeTKaV9k/edit?usp=sharing The script with the issue is called Ability Price Calculator.

Upvotes: 1

Views: 722

Answers (1)

Antoine Colson
Antoine Colson

Reputation: 656

It seems the problem was that function CalculateCost did not return anything...

function CalculateCost(abilityValues,index,level) {
  var ui = SpreadsheetApp.getUi();                                
  var ss = SpreadsheetApp.getActive();                           
  var sheet = ss.getActiveSheet();                                
  ui.alert("CalculateCost");
  FindRequirements(abilityValues,index,sheet,level); 
  // current function returns nothing!  
} 

/* You may have thought, "oh but CalculateCost() already does the return, 
so there's no need". However, when we call a function that contains 
a return, it's as though we just paste the value that it returns. 
Plus, there was no command (alert, prompt, etc) at the end of your 
non-return-function, which made no sense. It made no sense to Google
at least, so it was... undefined. */

So I changed it to

function CalculateCost(abilityValues,index,level) {
  var ui = SpreadsheetApp.getUi();                                
  var ss = SpreadsheetApp.getActive();                             
  var sheet = ss.getActiveSheet();                                 
  ui.alert("CalculateCost");
  var reqs = FindRequirements(abilityValues,index,sheet,level); // notice the reqs var   
  return reqs; // this line was missing
} 

Besides, I ran into problems when troubleshooting your code: my main issue was that when we click on CalculateCost in the menu, we normally expect to call the CalculateCost() function, however we actually call the InputValues() function. It's easy to get lost when custom functions are not tied to the same menu item, so maybe you could change that later.

Please, could you let me know if my answer helped you with your code?

Upvotes: 1

Related Questions