How to use functions in Squirrel?

1.1k views Asked by At

I am calling a simple function in my squirrel code, but this does not seem to work as expected. Calling the function with parameters does not affect the original variable. 'counter1' just keeps the same value. In javascript this would work, so why doesn't this work in Squirrel?

// declare test variable
counter1 <- 100;

function impLoop() {
  // function call to update these variables - this is not working!
  changeValue(counter1);
  // this just displays the original value: 100
  server.log("counter 1 is now " + counter1);

  // schedule the loop to run again (this is an imp function)
  imp.wakeup(1, impLoop);
}

function changeValue(val1){
    val1 = val1+25;
    // this displays 125, but the variable 'counter1' is not updated?
    server.log("val1 is now " + val1);
}
1

There are 1 answers

0
pheasant On BEST ANSWER

In Squirell bools, integers and float parameters are always passed by value. So when you modify val1 in function changeValue, you actually modify a formal parameter of the function initialized with the copy of the counter1 variable, not affecting val1. Javascript code would behave the same way.

To affect the value of counter1, you can use explicit assignment:

function changeValue(val1){
   val1 = val1+25;
   return val1;
}
...
counter1 = changeValue(counter1);

or pass counter1 as a slot of a table:

table <- {};
table.counter1 <- 100;

function changeValue(t){
    t.counter1 = t.counter1 + 25;
}

for (local i=0; i<10; i++) {
   changeValue(container);
   server.log("counter 1 is now " + container.counter1);
}