This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
olie304's profile picture

Parse hexadecimal value from string

Started by olie304, 24 October 2017 - 01:22 AM
olie304 #1
Posted 24 October 2017 - 03:22 AM
Hello everyone, currently trying to make a program that gradiently cycles through many hexadecimal values to cause a cool gradient effect on the Radiant Lamp from thermal expansion. However the code I use for changing my rgb value to a hex value returns the hex value as a string, which is no bueno and gives an error when trying to use it as a color. I don't have this problem a lot because my hex values are usually predefined but I do not know how to parse a hex value from the string.

Code:

local radiantLamp = peripheral.wrap("back")

function rgbToHex(rgb)
	local hexadecimal = '0x'

	for key, value in pairs(rgb) do
		local hex = ''

		while(value > 0)do
			local index = math.fmod(value, 16) + 1
			value = math.floor(value / 16)
			hex = string.sub('0123456789ABCDEF', index, index) .. hex		
		end

		if(string.len(hex) == 0)then
			hex = '00'

		elseif(string.len(hex) == 1)then
			hex = '0' .. hex
		end

		hexadecimal = hexadecimal .. hex
	end

	return hexadecimal
end

local time = 0

while true do
local frequency = 0.3
local red = math.sin(frequency*time + 0) * 127 + 128
local green = math.sin(frequency*time + 2) * 127 + 128
local blue = math.sin(frequency*time + 4) * 127 + 128

local hexColor = rgbToHex({red,green,blue})

radiantLamp.setColor(hexColor)
time++
end

Exact error:

38: Failed to convert arg 'color', cause: 'No known conversion of value 0x80F31F to int'

Thanks.
Edited on 24 October 2017 - 01:25 AM
KingofGamesYami #2
Posted 24 October 2017 - 04:52 AM
https://stackoverflow.com/questions/27294310/convert-hexadecimal-to-decimal-number
olie304 #3
Posted 25 October 2017 - 03:49 AM
thx m8