lua-users home
lua-l archive

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


On Mon, Aug 24, 2015 at 5:00 PM, iain morland <iain@iainmorland.net> wrote:
> I read the description of table.sort in PiL but am still unsure over “lhs" and “rhs". I couldn’t see those mentioned anywhere (in the whole book - unless Robert can please correct me!). How would a person know to use myArray[lhs] < myArray[rhs] in the first place? Are there other terms that might be used in place of “lhs” and “rhs” to do other things with the array? I feel that I am missing a crucial piece of understanding about this.

That's purely an example function, with "lhs" and "rhs" used as
example parameter names. You can write any function you want which can
be as complex as you want. The only requirement is that the function
takes two parameters, each an element in the array, and returns true
if the first argument should come before the second argument in the
finished sort. Here's another example I used in a personal script to
sort a sports league standings table:

    table.sort( list, function( n1, n2 )
        local a = n1.confWins + n1.confLosses > 0 and n1.confWins /
(n1.confWins + n1.confLosses) or 0.01
        local b = n2.confWins + n2.confLosses > 0 and n2.confWins /
(n2.confWins + n2.confLosses) or 0.01
        if n1.wins + n1.losses > 0 and n2.wins + n2.losses > 0 and
n1.wins / (n1.wins + n1.losses) ~= n2.wins / (n2.wins + n2.losses)
then
            return n1.wins / (n1.wins + n1.losses) > n2.wins /
(n2.wins + n2.losses)
        elseif a ~= b then
            return a > b
        elseif n1.h2hWins ~= n2.h2hWins then
            return n1.h2hWins > n2.h2hWins
        elseif n1.pointDiff ~= n2.pointDiff then
            return n1.pointDiff > n2.pointDiff
        elseif n1.pointsAllowed ~= n2.pointsAllowed then
            return n1.pointsAllowed < n2.pointsAllowed
        else
            return n1.randomNumber > n2.randomNumber
        end
    end )

Here, "list" is the array I want to sort, and "n1" and "n2" are the
parameter names I arbitrarily chose to represent the arguments. This
particular function sorts the array based on overall win/loss
percentage unless tied, in which case it tries conference win/loss
percentage unless that is also tied. In that case, it goes through
several other tiebreakers until it finds one that isn't tied and sorts
based on that.

So you can write whatever function you want here. The lhs and rhs is
simply an example.