Re: explain enum type to me
- Posted by ghaberek (admin) Oct 15, 2014
- 1326 views
I think the documentation does a pretty good job of explaining it.
There is also a special form of enum, an enum type. This is a simple way to write a user-defined type based on the set of values in a specific enum group. The type created this way can be used anywhere a normal user-defined type can be use.
For example,
enum type RGBA RED, GREEN, BLUE, ALPHA end type -- Only allow values of RED, GREEN, BLUE, or ALPHA as parameters function xyz( RGBA x, RGBA y) return end function
However there is one significant difference when it comes to enum types. For normal types, when calling the type function, it returns either 0 or 1. The enum type function returns 0 if the argument is not a member of the enum set, and it returns a positive integer when the argument is a member. The value returned is the ordinal number of the member in the enum's definition, regardless of what the member's value is. As an exception to this, if two enums share the same value, then they will share the same ordinal number. The ordinal numbers of enums surrounding these will continue to increment as if every enum had a unique ordinal number, causing some numbers to be skipped.
(emphasis mine)
So there you have it. This explains the behavior you're seeing in black-and-white.
include std/console.e enum type rgb red, green=3, blue, alpha=1 end type
Why is there aliasing?
Because red and alpha are both equal to 1. The internal values for the enum type are {1, 3, 4, 1} and so it never gets to that second 1.
Euphoria doesn't really know that red and alpha are named differently. As long as their value is within the list of "good" values, it passes the test.
Here is a basic example of what enum type does with a plain enum and a plain type.
enum red, green=3, blue, alpha=1 constant rgb_values = {red, green, blue, alpha} type rgb( object x ) return find( x, rgb_values ) end type puts( 1, "rgb_values = " ) ? rgb_values -- {1,3,4,1} ? rgb( red ) -- 1 ? rgb( green ) -- 2 ? rgb( blue ) -- 3 ? rgb( alpha ) -- 1 (because alpha=red)
Hope that helps,
-Greg