lua-users home
lua-l archive

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


On Mon, Dec 20, 2010 at 11:23, starwing <weasley.wx@gmail.com> wrote:
> but what if I don't know the amount of multi return values?

Sorry, there is no way to store multi-values without tables. You could
try closures, but Lua don't allow inner functions to reference vararg
upvalue. An intermediate solution is to memoize functions with the
necessary arity. For instance:


local _wrap = {}
function wrap( ... )
    local n = select( '#', ... )
    local f = _wrap[ n ]
    if not f then
        print( ': creating ' .. n .. '-ary closure' )
        local args = ''
        local base = string.byte( 'a' ) - 1
        for i = 1, n do
            args = args .. ', ' .. string.char( base + i )
        end
        args = string.sub( args, 3 )
        local prototype = string.format(
            'return function( %s ) return function() return %s end end',
            args, args )
        f = loadstring( prototype )()
        _wrap[ n ] = f
    end
    return f( ... )
end

function test( ... )
    print '--'
    local w = wrap( ... )
    print( w() )
    print( w() )
end

test( 1 )
test( 'a' )
test( 1, 2, 3, 4 )
test( 4, 5 )
test( function() end, {} )



But then, avoiding to use tables to use closures don't help you much
memory-wise.

--rb