I'm trying to write a simple quick sort function for lua. I keep getting a weird error though when I execute the function. First I'll show ou my function then I'll explain.
function quickSort(sortTable)
local lower, higher, pivot, pivotValue = {}, {}, 1, tonumber(sortTable[pivot])
if (#sortTable <= 1) then
return sortTable
end
for i = 1, #sortTable do
if (tonumber(sortTable[i]) > pivotValue) then -- error occurs here
table.insert(higher, sortTable[i])
else
table.insert(lower, sortTable[i])
end
end
return quickSort(lower), quickSort(higher)
end
When I run this code with a table that only contains numbers (example: {1,4,2,6,9}) which is what I wrote this to sort, I get the error
programName:lineWhereErrorOccurs: attempt to compare nil with number
.I don't have a clue which one is nil nor why it is even throwing that error in the first place because all table positions should be numbers. When I ran this on my "real" lua interpreter the call traceback showed that the error occurs on the first iteration of quickSort(). Is there anything I'm missing here? or is this just my bad luck?