10

When using web3, calling a function that returns an enum type converts it to a uint. Initially I assumed that enums are converted incrementally: 0,1,2,3.... However what I received was a hexadecimal. How is it converted, and how do you parse it?

For example:

contract Foo {
   enum Letter {A, B, C}
   function say(uint index) returns (Letter) {
       if(index == 0) return Letter.A;
       if(index == 1) return Letter.B;
       if(index == 2) return Letter.C;
       throw;
   }
}

If you call Foo.say.call(1) you get a hex number (0x3ad324...). How would I check if it was Letter.A or 'Letter.B` that was returned?

17

Enum values are numbered in the order they're defined, starting at 0. So, Letter.A will be 0, Letter.B will be 1, and so forth. There's currently no means to cast an enum value to its name; that information isn't retained at runtime.

  • I thought this was the case as well! However what I got from web3 were hashes, not incremental numbers. – latrasis May 20 '16 at 15:11
  • 1
    @latrasis You haven't included any web3 code in your question, so I can only speculate. Perhaps you're sending a transaction instead of making a local call, in which case you're getting back a transaction hash? – Nick Johnson May 20 '16 at 15:24
  • I just realized I forgot to add constant, you were right, thank you! – latrasis May 21 '16 at 20:34
3

About Enums, being described below:

nums are one way to create a user-defined type in Solidity. They are explicitly convertible to and from all integer types but implicit conversion is not allowed. The explicit conversions check the value ranges at runtime and a failure causes an exception. Enums needs at least one member.

Enum values are numbered in the order they're defined, starting at 0. If you want get value of enum, calling uint(enum_variable).

pragma solidity ^0.4.4;

contract SimpleEnum {

  enum VirtualTrade {DEFAULT,ONE,TWO}
  VirtualTrade vt;

    function SimpleEnum(){
        vt = VirtualTrade.DEFAULT;
    }

  function setValues(uint _value) {
      require(uint(VirtualTrade.TWO) >= _value);
      vt = VirtualTrade(_value);
  }

  function getValue() constant returns (uint){
      return uint(vt);
  }

}

Hope it helps~

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.