0

我在松鼠代码中调用了一个简单的函数,但这似乎没有按预期工作。带参数调用函数不会影响原始变量。'counter1' 只是保持相同的值。在 javascript 中这会起作用,那么为什么这在 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);
}
4

1 回答 1

4

在 Squirell bools 中,整数和浮点参数总是按值传递。所以当你val1在函数中修改时changeValue,你实际上是修改了用该变量的副本初始化的函数的一个形参counter1,而不影响val1. Javascript 代码的行为方式相同。

要影响 的值counter1,可以使用显式赋值:

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

counter1或作为表的插槽传递:

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);
}
于 2014-06-06T17:27:10.420 回答