Is it possible to generate a non-local variable with a function?

Weird question but it's for an exercise my senior asked me to do, I've scoured the web for an answer to no avail.

Instead of declaring the variable:

contract MetaCoin{
 uint counter=0;

Maybe do something like:

contract MetaCoint{
function createCounterVariable(){
  //creates counter variable

It will be functionally identical to the declaring the variable, and other functions can access the generated variable somehow. At least this is how I interpret what I'm supposed to do.

2 Answers 2


You could do something like this:

contract MetaCoint {
    uint public index;
    mapping(uint => uint) public counters;

    function addCounter() external {

    function incCounter(uint _index) external {
        require(_index < index, "counter was not created");
  • This is okay, but I think an array is more natural. (It avoids having to separately track the length, and it does the bounds checking automatically.)
    – user19510
    Commented Jun 5, 2019 at 5:32
  • @smarx: Yes, I agree. Since counters will be added sequentially, there is really no point in a mapping here. I now understand your solution, which is a better (more simplified) solution for the given problem as it is currently stated. Commented Jun 5, 2019 at 5:36

This really depends on what you're trying to do. There's really no such thing as "creating" a state variable. But you might be able to accomplish what you want with a mapping or array. Something like this (untested):

contract Counters {
    uint256[] public counters;
    event NewCounter(uint256 index);

    function createCounter() external {
        counters.push(0); // "create" a new counter
        emit NewCounter(counters.length - 1); // so the caller can see the ID of the new counter

    function increment(uint256 index) external {
        counters[index] += 1;
  • I think I've seen something like accessing the storage of the contract directly like an array, I could be wrong though.
    – ly6161
    Commented Jun 5, 2019 at 5:16
  • A little confusing, because there is no mapping here. Commented Jun 5, 2019 at 5:20
  • @goodvibration I suggested using a mapping or an array. I only gave one example, and it uses an array. Does that clear up your confusion?
    – user19510
    Commented Jun 5, 2019 at 5:32
  • Yes, I just figured that a mapping would address the issue more accurately, but as you initially stated, it really depends on what this dude is trying to achieve... Commented Jun 5, 2019 at 5:33
  • My interpretation is something like this ethereum.stackexchange.com/questions/69931/… but creating a new variable instead of accessing an existing variable, not sure if it can be done.
    – ly6161
    Commented Jun 5, 2019 at 7:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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