Example: Overloading Array Indexing Syntax

This example demonstrates a simple use of operator overloading with the [] (array indexing) operator. We create an object class (hexRGB_doc) whose only purpose is to provide an easy way to convert web-style hexadecimal color specifications to three-element RGB vectors.

The hexRGB_doc object definition and operator overloading code listed in this section is contained in the procedure file hexrgb_doc__define.pro, and is located in the examples/doc/objects subdirectory of the IDL distribution. To view the file in an IDL editor window, enter .EDIT hexrgb_doc__define.pro at the IDL command line.

The following code, located in hexrgb_doc__define.pro, defines the hexRGB_doc object and the overloaded [] (array indexing) operator method.

 

FUNCTION hexrgb_doc::_overloadBracketsRightSide, isRange, sub1

 

   ; Check to see that the input is a single, six-character string.

   ; If not, generate an error.

   IF (N_ELEMENTS(sub1) NE 1 || $

      SIZE(sub1, /TYPE) NE 7 || $

      STRLEN(sub1) NE 6 ) $

      THEN BEGIN

 

      MESSAGE, 'Input must be a single, six-character string'

 

   ENDIF ELSE BEGIN

 

   ; Read the input string, using the 'z' format code

   ; to convert from hexadecimal to floating-point values.

   READS, sub1, red, green, blue, FORMAT='(z2,z2,z2)'

 

   ; Create the return RGB array, converting to integer type.

   retval = FIX([red, green, blue])

 

   ENDELSE

 

   RETURN, retval

 

END

 

PRO hexrgb_doc__define

 

   STRUCT = { hexrgb_doc, $

   INHERITS IDL_Object }

 

END

The following code snippet creates a hexRGB_doc object and uses it to convert a hexadecimal color value to a three-element RGB vector.

c = hexrgb_doc()
PRINT, c['FF2C9D']

You could use this method to supply color values to IDL routines or keywords that expect a three-element RGB vector. For example:

p = PLOT(INDGEN(10), COLOR=c['FF00CC'])