0

The pop() functions works correctly for normal arrays and mappings.

Based on: How to delete an element at a certain index in an array?

When I try to pop() an array of a mapping not work.

Any alternative to remove the gaps?

pragma solidity ^0.8.0;

// SPDX-License-Identifier:

contract test {

mapping (address => uint[]) MyMap;

constructor(){
    MyMap[msg.sender].push(0);
    MyMap[msg.sender].push(1);
    MyMap[msg.sender].push(2);
    MyMap[msg.sender].push(3);
}

//Set last into [2] //1
MyMap[msg.sender][2] = MyMap[msg.sender][MyMap[msg.sender].length - 1];
//Delete last array position
MyMap[msg.sender].pop(); //This line is the problem...

}

JTCon
  • 703
  • 5
  • 16

2 Answers2

1

It always helps to show the full code and error. I'm not entirely sure what OwnerIndexes is, because it's not defined in the example. This line MyMap[msg.sender][2] = MyMap[msg.sender][MyMap.length - 1]; should however also be invalid, since MyMap is a mapping and does not have a .length attribute. You probably are looking for MyMap[msg.sender].length.

phaze
  • 1,575
  • 4
  • 12
  • OwnerIndexes is MyMap (I forgot change it) I am going to try with your suggestion. Thanks! – JTCon May 13 '22 at 16:58
  • You are right with the .lenght of array. That fixed that line. Now the problem is when calling the .pop() function--> MyMap[msg.sender].pop(); Any idea? Thanks – JTCon May 14 '22 at 02:08
  • well.. is this exactly the code that you are executing? The constructor part is only added at the end of a contract's deploy code. meaning the pop() would be called before the push. You cannot pop() an array if it is empty. Although then the line before would also be incorrect. Can you show the full code and error message? – phaze May 14 '22 at 11:51
0

Answer by leonardoalt in Solidity github:

"Popping an array of mappings is not allowed because you don't know which keys are dirty or not, so the deleting of the mapping does not actually happen. If you have an array of mappings, write to it, delete the array, and read the mapping again, the information is still there. Please see https://docs.soliditylang.org/en/v0.8.13/security-considerations.html#clearing-mappings."

Source: https://github.com/ethereum/solidity/issues/13021#issuecomment-1126682792

JTCon
  • 703
  • 5
  • 16