0
pragma solidity ^0.4.24;

contract Count {
    uint256 storeddata;

    function set(uint256 x) public {
        storeddata = x;
    }

    function get() public view returns(uint256) {
        return storeddata; 
    }
}

This is my code now, i'm trying to save more then one value on Blockchain but i can't know how many numbers to save.

So for example i have a table of 10 text field in my HTML but i need to save only 3 numbers... how can i do this? Is it good to use an array or there is something better in terms of costs ?

0

It's likely better if you use a mapping or an array, depending on your needs.

Here's an example of a hashmap, which is useful if you need to be able to efficiently insert/look-up, but not iterate:

pragma solidity ^0.4.24;

contract Count {
    mapping(string => uint256) private storedData;

    function set(string key, uint256 value) public {
        storedData[key] = value;
    }

    function get(string key) public view returns(uint256) {
        return storedData[key]; 
    }
}

Here's an example if you just want to iterate by index

pragma solidity ^0.4.24;

contract Count {
    uint256 private storedData;

    function set(uint256 index, uint256 value) public {
        storedData[index] = value;
    }

    function push(uint256 value) public {
        storedData.push(value);
    }

    function get(uint256 index) public view returns(uint256) {
        return storedData[key]; 
    }
}
  • Ok, but if i have a fixed number of fields for example 10, and i have to insert only 5 numbers, i will write the numbers in the first five fields, the others will be blank and i press the button to send information... my contract will run as if i have 10 numbers or only 5?suppose to don't use iteration – Simone R.C. Feb 1 at 15:59
  • If you fill in 5 of 10, then your front-end would just generate 5 transactions to the Count contract calling set with the filled values – flygoing Feb 1 at 16:24
  • Ok, perfect and another thing, what about if i want see all i have stored till now? @flygoing – Simone R.C. Feb 8 at 10:41
  • You have two choices for that. 1. You can emit an event when you add/remove something to the mapping and get all the events to reconstruct what exists. That's cheaper on gas, or 2. You can just use an array instead of (or as well as) a mapping and iterate by index. – flygoing Feb 8 at 13:31
  • ok i think i will choose the cheaper one, thank you! – Simone R.C. Feb 8 at 13:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.