If you’ve done any HTML work you’re probably familiar with setting colors using hexadecimal values, such as #FFFFFF for white, #000000 for black, and #FF30F0 for a weird pinkish-purple color.
But in Corona SDK you set colors using those odd base-10 numbers, so that last color would be set using something like:
blob:setFillColor(255, 48, 249)
I don’t know of anyone who works in decimal values for colors, so I’m not sure why Ansca used that convention, but I, for one, welcome our new decimal overlords.
Except when nobody was looking I created a handy little function that allows me to use “normal” color numbers in my Corona code. Here’s an example:
blob:setFillColor( convHexColor( "FF30F0" ))
The convHexColor takes the string of hex numbers I pass it and passes back the decimal numbers the setFillColor() function needs. Here’s that short little function:
function convHexColor(hex) local r = hex:sub(1, 2) local g = hex:sub(3, 4) local b = hex:sub(5, 6) return tonumber(r, 16), tonumber(g, 16), tonumber(b, 16) end
What makes it really cool are two thing:
1. Lua allows you to pass back multiple values.
For someone coming from a “normal” programming language this is just plain weird. And awesome. So we can pass back the numbers representing red, green and blue all at one time.
2. The Lua tostring() function allows you to specify the base of the number you’re working with.
The default is base-10 (our human-normal system) so if you do tonumber(“14”) you’ll get back the decimal number 14. But if you add a second parameter you can pass in a hex string and get back decimal, so tonumber(“E”, 16) will give you back the decimal number 14.
So the convHexColor() function pulls the red, green, and blue parts from the string that is passed (so it requires this format: RRGGBB) and then runs each of those through tonumber() with base-16 requested, and finally returns those three numbers.
Rocket science? Nah, just a shortcut to make game development easier.
PS – It’s quite possible there’s a better way to handle this problem. If so, don’t be shy, pipe up and let me know the error of my ways.