lua-users home
lua-l archive

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


If you're sorting a large table you will execute <string>:upper() a lot. Caching this can speed up thing, especially for long strings:

local function ss2(t)
    local uptable = setmetatable({},{
        __index = function(t,k)
            local v = k:upper()
            t[k] = v
            return v
        end})
    local function cmp(a,b)
        local upa, upb = uptable[a], uptable[b]
        if upa ~= upb then
            return upa < upb
        else
            return a < b
        end
    end
    table.sort(t, cmp)
end


On 12/18/2009 05:34 AM, Peter Cawley wrote:
On Fri, Dec 18, 2009 at 1:27 PM, Jeff Pohlmeyer
<yetanothergeek@gmail.com>  wrote:
table.sort(t, function (a, b) A=a:upper() B=b:upper() return A==B and a<b or A<B end);
a<b can be false, so the implicit-if is not appropriate. You'd have to
use an explicit-if:

table.sort(t, function (a, b)
   local A,B =a:upper(), b:upper()
   if A == B then return a<  b
   else return A<  B
end end)