Sorting by Object Number (improved)

int legalCompare(string s1, string s2)

This function is a far more efficient way of comparing object numbers. Object numbers are legal paragraph numbers of the form 1.1, 1.2, 1.2.1 etc.

// Example usage
if (legalCompare("1.10","1.5") == 1)
{
    print("We want to see this")
}

This function was originally developed as a callback function for sorting a column in a listView. For this reason, when bad parameters are passed it returns zero (no sorting applied). This can be changed by changing the return statement immediately after the lastError call.

Source code:

//  Comparison function for legal paragraph numbers.

/*
	This function can be used as a callback sort function to
	sort a listview column containing 	legal paragraph numbers,
	1.0, 1.1, 1.1.1 etc.

	Function returns an integer value as follows:

		s1 == s2, returns 0
		s1 > s2, returns 1
		s2 > s1, returns -1

	If either of the parameters are not correctly formatted
	legal paragraph numbers then the function returns 0.

	If you are using this function elsewhere, i.e. not as a listView
	callback, then it can be be changed to return another number on error,
	say 2, 	by altering the return statement immediatly after the
	lastError command.

	This function relies on the fact that intOf() will return
	an ingeter if the first part of the string can be interpreted
	as an integer, regardless of the remainder, which is ignored.

	i.e. intOf("1.2") returns 1.

	If the integers being compared are equal, the the function
	recurses with the remainder of the string.

	isValidInt() cannot be used to check the string before calling
	intOf() because it will return false unless the whole string
	can be interpreted as an integer.

	i.e. isValidInt("1.2") returns false.

	Instead, calls to intOf() are surrounded by a noError...lastError
	construct to capture bad parameters.

	Tony Goodman
*/

int legalCompare(string s1, string s2)
{
	int i1 = 0
	int i2 = 0

	noError

	i1 = intOf(s1)
	i2 = intOf(s2)

	if (lastError != "")
	{
		return(0)
	}

	if (i1 > i2)
	{
		return(1)
	}
	else if (i2 > i1)
	{
		return(-1)
	}
	else
	{
		if (length(s1) > length(i1 ""))
		{
			if (length(s2) > length(i2 ""))
			{
				return(doSortLegal(s1[length(i1 "") + 1:], s2[length(i2 "") + 1:]))
			}

			return(1)
		}
		else if (length(s2) > length(i2 ""))
		{
			return(-1)
		}

		return(0)
	}

	return(0)
}