0

In a game I'm working on, I have an advancement system that is supposed to trigger based on exponent levels:

function machinesOwnedAdvancement(machine,machineLevel) {
  if (machine >= Math.pow(2,(machineLevel+5))) {
    console.log(machineLevel);
    machineLevel += 1;
    console.log("Machine is upgraded. It is now level: " + machineLevel);
  }
}

The function will be called as such:

machinesOwnedAdvancement(scribes, scribesAdvancementLevel);

Where scribes is number of machines owned, and scribesAdvancementLevel is initially = 0. The idea is that it 'should' add 1 to the advancement level. The console.log suggests it does, but when the next game tick occurs (i.e. the function is called again), the console.log(machineLevel) is still at 0.

Maybe I'm mistaken about how function arguments can be used to manipulate variables??

1 Answers1

1

machineLevel is a local variable, which means that whenever the function exists, it discards that variable. You should return a value, and then store it in a variable which you can later pass down.

Here's a very simple example.

let scribe = 10,
    advancementLevel = 1;

function machinesOwnedAdvancement(machine,machineLevel) {
  if (machine >= Math.pow(2,(machineLevel+5))) {
    console.log(machineLevel);
    machineLevel += 1;
    console.log("Machine is upgraded. It is now level: " + machineLevel);
  }
  return machineLevel;
}

advancementLevel = machinesOwnedAdvancement(scribe, advancementLevel);
console.log(advancementLevel);
Keno
  • 2,018
  • 1
  • 16
  • 26
  • How does one return to the same external variable parsed in to the function though without explicitly naming it within the function? Because the plan was to save having to type a variant of the same function 12 times... So, in this example, how do you return scribesAdvancementLevel = machineLevel without explicitly naming it? Thanks :-) – Jon McCallum Mar 01 '19 at 12:05
  • @JonMcCallum I've added a code sample which might help you to understand how it works. – Keno Mar 01 '19 at 12:07
  • Yes I saw. Makes sense, thanks so much for the help. So much to learn, so little time! – Jon McCallum Mar 01 '19 at 12:08
  • @JonMcCallum Happy to help, and welcome to Stack Overflow. If this answer solved your issue, please mark it as accepted :) – Keno Mar 01 '19 at 12:12