[Ethereum] does EVM support pop() that returns the last element

evm

pop() that returns the last element is a method I have found would be good to have in smart contract development. Since v0.5.0 released a year ago, Solidity supports pop() for removing the last element of an array, but without returning it. Do other languages like Vyper support pop() (with last element returned), is there any plans for Solidity to support it, is the logic easily implemented in assembly?

edit: more or less pop() with assembly for 2 dimensional array.

function pop(uint _arraySlot, uint _idx) public returns (uint popped) {
    assembly {
        let arrayData:= keccak256(_arraySlot)
        let len := sub(sload(add(arrayData, _idx)), 1)
        popped := sload(add(keccak256(add(arrayData, _idx)), len))
        sstore(add(arrayData, _idx), len)
    }
}

Best Answer

The EVM supports POP as an opcode, but that's not what you want. That just pops an item from the stack and discards it, which has nothing to specifically do with arrays. The feature you want, the ability to pop from an array and return the element, is something implemented in a high-level language, like Solidity or Vyper. There is no native support in Solidity to pop, and Vyper doesn't even support dynamic sized arrays, only fixed ones, so pop wouldn't even make sense. There aren't plans to support it afaik in either language. That said, it is very simple to do what you want without dropping into assembly, and with fewer LOC even:

function pop(uint256[] storage array) internal returns (uint256){
    uint256 item = array[array.length-1];
    array.pop();
    return item;
}
Related Topic