I am calling a simple function in my squirrel code, but this does not seem to work as expected.
Calling the a function with parameters does not affect the original variables. ‘counter1’ and ‘counter2’ just keep the same value. In javascript this would work, so why doesn’t this work in Squirrel?
`// declare test variables
counter1 <- 100;
function impLoop() {
// function call to update these variables
changeValue(counter1);
server.log("counter 1 is now " + counter1);
// schedule the loop to run again:
imp.wakeup(1, impLoop);
}
function changeValue(val1){
// shouldn’t this increase the value of counter1?
val1 = val1+25;
}`
counter1 is a global variable, set to 100. The variable val1 in the function changeValue() is local to that function, ie. only that function ‘knows’ about it.
Your code essentially copies the value in counter1 into val1 when you pass counter1 to the function changeValue(). You then change the value of val1 (to 125; at this point counter1 is still 100) but you don’t hand back the answer. There are at least two ways to do this, but given you’re using a function, the best is to change your functions thus:
function changeValue(val1) { // shouldn't this increase the value of counter1? NO!! val1 = val1+25; return val1 // return the sum's answer }
and
`function impLoop()
{
// function call to update these variables
counter1 = changeValue(counter1);
server.log("counter 1 is now " + counter1);
// schedule the loop to run again:
imp.wakeup(1, impLoop);
}`
Here, counter1 is updated with the value ‘returned’ by the function changeValue()
In Squirrel, single values (numbers, strings, booleans – known collectively as “scalars”) are “passed by value”. That means that “val1” in the function changeValue is a copy of the variable counter1, and changes made to it aren’t reflected in the original – it’s not copied back again.
By contrast, compound values (arrays, tables, class instances) are “passed by reference”, which means that the variable in the function is a reference to the original and changes made to it are visible from the outside.
Exactly the same is true in Javascript, BTW:
`var counter1 = 100;
Thanks for the clarifications! There’s some confusion on my part apparently.
I’m going to try and use an object instead of passing a straight number.
(I can’t use return values because ultimately I need to change several different parameters with one function).