getColorWildcard fix

Post Reply
Jor'Mox
Posts: 1142
Joined: Wed Apr 03, 2013 2:19 am

getColorWildcard fix

Post by Jor'Mox »

So, here is the getColorWildcard function from the Other.lua file as is (with a few new lines put in for readability).
Code: [show] | [select all] lua
function getColorWildcard(color)
	local color = tonumber(color)
	local startc
	local endc
	local results = {}

	for i = 1, string.len(line) do
		selectSection(i, 1)
		if isAnsiFgColor(color) then
			if not startc then 
				if i == 1 then 
					startc = 1
				else
					startc = i + 1
				end
			else 
				endc = i + 1
				if i == line:len() then
					results[#results + 1] = line:sub(startc, endc)
				end
			end
		elseif startc then
			results[#results + 1] = line:sub(startc, endc)
			startc = nil
		end
	end
	return results[1] and results or false
end
As is, it has a couple of problem. First, it starts at the second character, but doesn't realize it (the first character position for selectSection is 0, not 1). So that is an easy fix, just change the 1 to a 0 in the for loop. It also means the if statement looking at i to set startc isn't needed, and startc can always be i+1. The second, bigger problem is that it doesn't work for single characters of a given color, and instead thinks the color continues to the end of the string. This is because it doesn't set endc until after a second character is found of that color, and string.sub with no second argument returns the rest of the string starting from the start point. This can be fixed by just declaring endc when startc is declared. Here is a corrected version.
Code: [show] | [select all] lua
function getColorWildcard(color)
	local color = tonumber(color)
	local startc
	local endc
	local results = {}

	for i = 0, string.len(line) do
		selectSection(i, 1)
		if isAnsiFgColor(color) then
			if not startc then 
				startc = i + 1
				endc = i + 1
			else 
				endc = i + 1
				if i == line:len() then
					results[#results + 1] = line:sub(startc, endc)
				end
			end
		elseif startc then
			results[#results + 1] = line:sub(startc, endc)
			startc = nil
		end
	end
	return results[1] and results or false
end

User avatar
Vadi
Posts: 5035
Joined: Sat Mar 14, 2009 3:13 pm

Re: getColorWildcard fix

Post by Vadi »

It looks like the buggy version is still there: https://github.com/vadi2/mudlet-lua/blo ... r.lua#L515

Mind submitting a PR? Just hit the edit button on the top of the file (once logged in), drop your new function in and follow the instructions:

Image

Jor'Mox
Posts: 1142
Joined: Wed Apr 03, 2013 2:19 am

Re: getColorWildcard fix

Post by Jor'Mox »

Okay, I think I did that successfully.

User avatar
Vadi
Posts: 5035
Joined: Sat Mar 14, 2009 3:13 pm

Re: getColorWildcard fix

Post by Vadi »

Looks good! Appreciated.

Post Reply