lua-users home
lua-l archive

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



On 11-Mar-05, at 4:25 PM, PA wrote:

Hello,

I would like to sort a table of tables (sic).

To do that I was hoping to use table.sort( aTable, aComparator ), where 'aComparator' is my own function. Something like this perhaps:

        -- instance method to compare the two given services
        this.compare = function( anObject, anotherObject )
                local aLength = string.len( anObject.prefix() )
                local anotherLength = string.len( anObject.prefix() )

                return aLength > anotherLength
        end


Presumably, it's not exactly like that since that function will always return false, barring some chicancery with the implementation of anObject.prefix().

In fact, a slightly corrected version of that works just fine:

rlake@freeb:~/lualib$ lua
Lua 5.0.2  Copyright (C) 1994-2004 Tecgraf, PUC-Rio
> function populate(x)
>> local rv = {}
>> for word in string.gfind(x, '%S+') do
>>   local _, _, prefix, suffix = string.find(word, '([^%-]*)-(.*)')
>>   table.insert(rv, {prefix = prefix, suffix = suffix, word = word})
>> end
>> return rv
>>end
> function show(t) for _, entry in ipairs(t) do print(entry.word) end end > t = populate [[ antidis-establishmentarianism pro-active infra-structure a-uno ]]
> show(t)
antidis-establishmentarianism
pro-active
infra-structure
a-uno
> function compare(a, b) return string.len(a.prefix) < string.len(b.prefix) end
> table.sort(t, compare)
> show(t)
a-uno
pro-active
infra-structure
antidis-establishmentarianism

Unfortunately, table.sort() throws an exception:

lua: attempt to compare two table values

...snip

Why is that? Why can't I "compare two table values"? Am I doing something wrong?

If I were to speculate, which I have to in the absence of actual details, I would guess that you misspelled the name of the comparator function, thereby passing table.sort nil as its second argument which indicates the default comparator, <. < doesn't work on tables:

> table.sort(t, compere)
attempt to compare two table values
stack traceback:
        [C]: in function `sort'
        stdin:1: in main chunk
        [C]: ?