More effecient way to write this

Hey everyone! I’ve been playing a lot with generating geometry lately, and I’ve stumbled upon this (and similar) issues.

The code below basically sorts a table based on where the 2 coordinates are located. xWall and zWall are booleans. xWall is true when the Z coordinates of the 2 coordinates are the same. zWall is the same, but when the X coordinates are the same. One of them is always true. I now want to sort a table based on the X coord (or Z coord depending on wether xWall or zWall is true).

My question goed as follows: Is there a more efficient way to write this. Performance is not really an issue here but I just want it to look cleaner. Here is the current code:

	-- Sort the windows by coordinate
	table.sort(windows, function(valueA, valueB)
		if xWall then
			if cornerA.X > cornerB.X then
				return valueB.Position.X < valueA.Position.X
			else
				return valueB.Position.X > valueA.Position.X
			end
		elseif zWall then
			if cornerA.Z > cornerB.Z then
				return valueB.Position.Z < valueA.Position.Z
			else
				return valueB.Position.Z > valueA.Position.Z
			end
		end
	end)

First, I am assuming you meant valueA.Position.X < valueB.Position.X in your first if statement, otherwise table.sort would not sort correctly.
As for your question, this can be done a bit more efficiently:
local function cmp(valueA, valueB)
if xWall then
if cornerA.X > cornerB.X then
return valueA.Position.X < valueB.Position.X
else
return valueA.Position.X > valueB.Position.X
end
elseif zWall then
if cornerA.Z > cornerB.Z then
return valueA.Position.Z < valueB.Position.Z
else
return valueA.Position.Z > valueB.Position.Z
end
end
end

table.sort(windows, cmp)

You can also use the ternary operator:
local function cmp(valueA, valueB)
if xWall then
return cornerA.X > cornerB.X and valueA.Position.X < valueB.Position.X or valueA.Position.X > valueB.Position.X
elseif zWall then
return cornerA.Z > cornerB.Z and valueA.Position.Z < valueB.Position.Z or valueA.Position.Z > valueB.Position.Z
end
end

table.sort(windows, cmp)