lua-users home
lua-l archive

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


On Apr 4, 2011, at 9:43 PM, Patrick Donnelly wrote:

> On Mon, Apr 4, 2011 at 9:48 AM, Jerome Vuarand <jerome.vuarand@gmail.com> wrote:
>> You can use coroutines, but I don't think it's a better solution. For example:
>> 
> You can also handle nils:

And make it shorter:

local function argv( ... )
    local aFunction = function( ... )
        coroutine.yield()
        
        for anIndex = 1, select( '#', ... ) do
            coroutine.yield( anIndex, select( anIndex, ... ) )
        end
    end
    
    aFunction = coroutine.wrap( aFunction )
    aFunction( ... )
    
    return aFunction
end

for anIndex, aValue in argv( nil, 'a', 'b', 'c', nil, 'd', nil ) do
    print( anIndex, aValue )
end

But why bother?

If anything, I prefer Benoit's original version, which simply create a table, and be done with it :)

local function argv( ... )
    return function( aList, anIndex  )
        anIndex = anIndex + 1
        if anIndex <= aList.n then
            return anIndex, aList[ anIndex ]
        end
    end, { n = select( '#', ... ), ... }, 0
end

Also, there is nothing fundamentally wrong with using select() directly :))