lua-users home
lua-l archive

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


PA wrote:
> For example, lets assume I have a function which would like to strip
> empty strings and replace them with, err, nil values, e.g.:
> 
> local function Argument( ... )
>      local someArguments = {}
> 
>      for anIndex = 1, select( '#', ... ) - 1 do
>          local aValue = select( anIndex, ... )
> 
>          if aValue:len() == 0 then
>              aValue = nil
>          end
> 
>          someArguments[ #someArguments + 1 ] = aValue
>      end
> 
>      return someArguments
> end
> 
> Lets assume this is used to cleanup the captures returned by
> string.match:
> 
> local someArguments = Argument( aValue:match( aPattern ) )
> 
> And then unpacked as a vararg to invoke a function:
> 
> aHandler( unpack( someArguments ) )
> 
> This is all good and well except that I cannot seem to find a way to
> 'round trip' those vararg properly as a table doesn't support nil
> values in the first place... but vararg does... in other words... how
> does one build a proper vararg at runtime with nil values and all
> which 
> is unpack friendly?!?!?
> 
> Any insight much appreciated!

You can store the argument count in the table :

local function Argument( ... )
    -- here store the number of arguments as key narg
    local someArguments = {narg = select( '#', ... )}
    
    -- select('#',...) is the rank of the last arg, the -1 is probably
superfluous
    for anIndex = 1, select( '#', ... ) - 1 do
        local aValue = select( anIndex, ... )
        
        if aValue:len() == 0 then
            aValue = nil
        end
        
        someArguments[ #someArguments + 1 ] = aValue
    end
    
    return someArguments
end
local someArguments = Argument( aValue:match( aPattern ) )
aHandler( unpack( someArguments, 1, someArguments.narg ) )