lua-users home
lua-l archive

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


Hello,

I guess I'm still completely confused about how to deal with vararg, table and nil values...

(1) vararg can have nil values

function dwim( ... )
    print( '#', select( '#', ... ) )

    for anIndex = 1, select( '#', ... ) do
        print( select( anIndex, ... ) )
    end
end

dwim( nil, true )

> 2
> 1       nil     true
> 2       true

2 arguments, the first is nil, the second is true

(2) table behavior seems to be, errr, confusing when confronted with nil values


local aTable = { nil, true }
print( #aTable )
> 2
-- Hmmm... two keys...


print( table.maxn( aTable ) )
> 2
-- table.maxn agrees, two keys


print( table.getn( aTable ) )
> 2
-- Even table.getn seems to agree, two keys


for aKey, aValue in pairs( aTable ) do
    print( aKey, aValue )
end
> 2       true
-- The pairs iterator seems to think there is only one key though


for aKey, aValue in ipairs( aTable ) do
    print( aKey, aValue )
end
-- And ipairs doesn't see any keys at all


This is all good and well, if slightly confusing... that said... how does one build a vararg at runtime considering all this?!?

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!

Cheers,

PA.