lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


> On Aug 26, 2015, at 1:44 PM, iain morland <iain@iainmorland.net> wrote:
> 
> Thank you for the further responses. I now see that rhs/lhs was a red herring!
> 
> Unfortunately I still don’t confidently grasp how the function works. Take the example in Roberto’s PiL book:
> 
> table.sort(network, function(a,b) return (a.name > b.name) end)
> 
> Presumably the function in the second argument returns true or false - right? Either a.name is greater than b.name or not.
> 
> But what are a and b? Does table.sort repeatedly call the function using successive pairs of items from the table ‘network’ as arguments a and b? 
> 
> And if the arguments passed to this function refer to a *different* table from that which is being sorted, where (in memory) is the sorting occurring? The other table doesn’t get sorted in-place, for its order remains the same.
> 
> I think the crux of my confusion is that the function in the second argument iterates, but it doesn’t look like an iterator - at least to the less trained reader.
> 
> Thanks
> Iain

Sorting a table is generic in the sense that the *process* of sorting can be handled by the table.sort() function internally, but the desired *order* of the sort is left up to you, as caller of the table.sort() function. To allow you to specify the desired order of the sort, you supply a “compare” function that defines the sort order. How does this work? As the table.sort() progresses, the sorter needs to be able to compare two arbitrary entries in the list of items being sorted (that is, the array within the table).

When the sorter calls your compare function, it is asking “Here are two of the items in the list you told me to sort .. please tell me which one should come first in the sort?”. The two items to compare are specified by the first and second arguments to the function you supply (you can give them any names you like). You return true if the first item should come before the second, false otherwise. The table.sort() function will call your “compare” function many times during the sort, comparing many different pairs of items as needed until the sort is complete.

For example:

t = { 10, 5, 99, -17 }

— Returns true if a is smaller then b, meaning sort will be smallest to largest
function comp1(a, b)
	print(“Comparing: “, a, b)
	return a < b
end

print(“Starting sort”)
table.sort(t, comp1)
print(“Done!”)


—Tim