[Ethereum] TypeError: Expression has to be an lvalue. But before the code was working perfectly!

soliditytruffletruffle-contract

I have changed a few things inside the function but the logic is the same still. Now, give an error in the compiler. I am USING TRUFFLE with VSC.

Former function:

function remove(uint ind) internal returns(address[]) {
    delete addressStorage[ind];
    for (uint j = ind; j<addressStorage.length;j++) {
        if (j==addressStorage.length-1) {
            break;
        }else {
            addressStorage[j] = addressStorage[j+1];
        }
    }
    addressStorage.length--;
    return addressStorage;
}

Actual:

function remove(uint ind, address[] array) internal returns(address[]) {
    delete array[ind];
    for (uint j = ind; j<array.length;j++) {
        if (j==array.length-1) {
            break;
        }else {
            array[j] = array[j+1];
        }
    }
    array.length--;
    return array;
}

Getting:

TypeError: Expression has to be an lvalue.
array.length–;
^———-^

Any ideas? Thanks!

Best Answer

Memory is temporary. Storage is permanent. For example, you would perform intermediate computations using memory, and then save the result to storage.

There are defaults for the storage location depending on which type of variable it concerns:

  1. state variables are always in storage
  2. function arguments are in memory by default
  3. local variables of struct, array or mapping type reference storage by default
  4. local variables of value type (i.e. neither array, nor struct nor mapping) are stored in the stack

When you pass address[] array as a function argument, solidity will save it in memory i.e. it will make a copy of the array. Changes made will not be permanent.

Add "storage" in the argument to solve the error.

function remove(uint ind, address[] storage array) internal returns(address[]) {
delete array[ind];
for (uint j = ind; j<array.length;j++) {
    if (j==array.length-1) {
        break;
    }else {
        array[j] = array[j+1];
    }
}
array.length--;
return array;

}

Related Topic