Skip to content
Advertisement

My local variable not updating the global var?

I have a global variable number, so it gets a pass to a function, but when it completed, it supposes to change that variable inside the function and pass it outside to the global variable to update. So it continuing to use old global variables while everything else is updating and become bigger.

var P_Level = 1

var E_Level = 1

var P_Current = 0

var P_Max = 100

function P_EXP_Gain(exp) {
    console.log('P_Max1 is '+P_Max)
    console.log('P_Current1 is '+P_Current)
    console.log('P_Level1 is '+P_Level)
    console.log("")
    if (exp == undefined || null) {
        P_Current = (E_Level * 20) + P_Current
        P_Max = P_Max
        P_Experience(P_Current, P_Max)
    }
    else {
        P_Current = ((E_Level * 20) + exp) + P_Current
        P_Max = P_Max
        console.log('P_Max2 is '+P_Max)
        console.log('P_Current2 is '+P_Current)
        console.log('P_Level2 is '+P_Level)
        console.log("")
        P_Experience(P_Current, P_Max)
    }
}

function P_Experience(P_Current, P_Max) {
    while (P_Current >= P_Max) {
        P_Level++ // There is a hidden error that causes one to gain perm level up every time they level up via normal way.
        P_Current = P_Current - P_Max
        P_Max = P_Level * 100
        console.log("")
        console.log('P_Max3 is '+P_Max)
        console.log('P_Current3 is '+P_Current)
        console.log('P_Level3 is '+P_Level)
        console.log("")
        alert('Level Up')
    }
}

P_EXP_Gain(80)
P_EXP_Gain(80) // notice that current random get extra 100
P_EXP_Gain(80)

You can see via console.log that right before while loop, it always have P_Max of 100, but after that, it change correctly, but that change never update to global P_Max. I also notice that after the first P_EXP_Gain, the P_current will increase by 100 in the first part of the function before it takes into account of gain. I am at a loss of why this is happening. Did I get math somewhere wrong?

https://jsfiddle.net/Necrorifter/Lc18tobw/9/

Advertisement

Answer

Your argument names for the P_Experience function are P_Current and P_Max and that is overriding the global scope within the function. Easiest solution is to rename the arguments

Advertisement