[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: lhs and rhs in table.sort
- From: Oliver Kroth <oliver.kroth@...>
- Date: Wed, 26 Aug 2015 23:41:31 +0200
Hi iain,
the thing works like this:
There is a generic sort algorithm that swaps two values if the rhs is
"larger than" the lhs. rhs is right-hand-side, lhs is left-hand-side and
refers to the left and right side of a < operator.
You don't have to know how the sort algorithm works, as long as you
provide it with a function that gives it a clue when to swap two values
of the array. You define the ordering, the sort function works based on
this.
E.g., you have a database with cars, and you want to sort them based on:
a) mileage
b) top speed
c) age,
you just provide to the generic sort() function a function that compares
the relevant fields in the records and returns the result.
If you are smart, you don't sort the data, but an index on it, and this
not more difficult, as you sort the index, and your comparison function
returns the result of the comparison of the two indexed values (instead
the comparison of the indices.)
More theoretical:
If on your data a comparison "<=" can be defined for which for any three
data a,b,c this is true: if a <=b and b<=c then a<=c, , you can sort them.
More practical:
Sorting is generic, the comparison function is custom specific. You just
call the sort() function and it will ask you (by calling back the
comparison function that you provided) which one of two value shall come
first. When the sort function is finished, it has sorted the array
according to your ordering function.
--
Oliver
Am 26.08.2015 um 22:44 schrieb iain morland:
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