Minimal Wx_Colour bug?

require ‘wx’

col_sample4.rb

BLACK = Wx::Colour.new(0,0,0)
RED = Wx::Colour.new(128,0,0)

@background_colour = BLACK
@symbol_colour = BLACK
temp_colour = BLACK
temp2_colour = RED

@symbol_colour = Wx::Colour.set(1, 0, 0)

puts “@background_colour : #{@background_colour}”
puts “@symbol_colour : #{@symbol_colour}”
puts “temp_colour : #{temp_colour}”
puts “temp2_colour : #{temp2_colour}”

=begin

Hypothetical Values:

@background_colour : #<Wx::Colour: (0, 0, 0 *255)>
@symbol_colour : #<Wx::Colour: (1, 0, 0 *255)>
temp_colour : #<Wx::Colour: (0, 0, 0 *255)>
temp2_colour : #<Wx::Colour: (128, 0, 0 *255)>

Actual Values:

@background_colour : #<Wx::Colour: (1, 0, 0 *255)>
@symbol_colour : #<Wx::Colour: (1, 0, 0 *255)>
temp_colour : #<Wx::Colour: (1, 0, 0 *255)>
temp2_colour : #<Wx::Colour: (128, 0, 0 *255)>

What’s going on here and how do I correct this problem?

=end

The fix:

@symbol_colour = Wx::Colour.new(1, 0, 0)

instead of

@symbol_colour.set(1, 0, 0)

works but it doesn’t it waste resources? Does someone have a better
soloution?

Thanks.

Hi Philip

What’s happening is that you have multiple variables referring to the
same object. When you change the object, all references change:

Philip S. wrote:

col_sample4.rb

BLACK = Wx::Colour.new(0,0,0)

A new object is created; the constant BLACK refers to this object

@background_colour = BLACK

The instance variable @background_colour now also refers to this same
object.

@symbol_colour = BLACK

Now so does the variable @symbol_colour

@symbol_colour = Wx::Colour.set(1, 0, 0)

Change the colour intensities of the (single) colour object. So all
references to it will reflect the change.

If you want to create an independent copy of a colour from a colour, use
the constructor:

my_black = Wx::Colour.new(Wx::BLACK)
Wx::BLACK == my_black # true
my_black.set(127, 127, 127)
Wx::BLACK == my_black # false

Don’t worry too much about resource control with colours, they will get
cleaned up automatically when they fall out of scope, and they are more
light-weight objects than say Pens and Brushes. Sometimes I find it
useful to declare a palette as a set of constants in a class.

class MyDrawingThing
SYMBOL_COLOUR = Wx::Colour.new(127,127,127)
HIGHLIGHT_COLOUR = Wx::Colour.new(Wx::RED)

etc

hth
a