Copy a color?
  • frostyfrosty February 18

    I ran into a little issue just now and wondered if there was an easy way around it. Is it possible to copy a color object?

    I have the following:

    -- global variable
    cLightBlue = color(0, 232, 216, 255)
    
    -- in a class, elsewhere:
    self.fillColor = cLightBlue
    self.fillColor.a = 100
    

    The problem is, this affects anything that uses the cLightBlue colour! So I presume self.fillColor is a reference to my global variable, rather than a copy of it.

    Any way around this, or do I manually need to copy each property of the color or something?

    Thanks all :)

  • SimeonSimeon February 18

    I think you'll need to manually copy, like this:

    
    self.fillColor = color( cLightBlue.r, cLightBlue.g, cLightBlue.b, cLightBlue.a )
    
    

    An alternative would be to define you colour constant as a factory function:

    
    cLightBlue = function() return color(0, 232, 216, 255) end
    
    self.fillColor = cLightBlue()
    
    

    Or define a colour-copy function

    
    function cc(c)
        return color(c.r,c.g,c.b,c.a)
    end
    
    self.fillColor = cc( cLightBlue )
    
    
  • SimeonSimeon February 18

    I didn't actually realise this was the case with user data values like color, vec2, and so on. I'm surprised I haven't run into the same issue in normal coding.

  • frostyfrosty February 18

    Great, thanks @Simeon. The factory function seems pretty neat :)

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Sign In with OpenID Sign In with Google

Sign In Apply for Membership

In this Discussion

Tagged