lua-users home
lua-l archive

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


On Nov 4, 2010, at 8:14 AM, <mail@umaxx.net> <mail@umaxx.net> wrote:

> can someone show me how to (re-)implement the pairsByKeys()-iterator from
> PIL sorting chapter (19.3) using coroutines?

Hmmm... not sure if this makes much sense, but, for example:

local function Sort( aMap )
    local aList = {}
    
    for aKey, aValue in pairs( aMap ) do
        aList[ #aList + 1 ] = aKey
    end
    
    table.sort( aList )
    
    return coroutine.wrap
    ( 
        function()
            for anIndex, aKey in ipairs( aList ) do            
                coroutine.yield( aKey, aMap[ aKey ] )
            end
        end 
    )
end


for aKey, aValue in Sort( { _ = 'zero', c = 'one', b = 'two', a = 'three' } ) do
    print( aKey, aValue )
end

> _	zero
> a	three
> b	two
> c	one