Lua 5.1 and support for the new vararg handling style:
function vfunc( ... ) for i = 1, select( '#', ... ) print( i, (select( i, ... )) ) end end
or if you really want varargs in the newly allocated table to call every function call (beware of nil arguments):
function vfunc( ... ) local args = {...} for i, v in ipairs( args ) do print( i, v ) end end
If you also need to support Lua 5.0, you're out of luck, because ... outside the parameter list is a syntax error. You need to resort to generating conditional code to get around this:
-- newer Lua versions use load instead of loadstring local loadstring = loadstring or load -- feature test for Lua 5.1+ local supports_ellipsis = loadstring( "return ..." ) ~= nil local args = supports_ellipsis and "{...}" or "arg" function vararg( n, f ) local t = {} for i = 1, n do t[ i ] = "_"..i end local params = table.concat( t, ", ", 1, n ) local code = [[ return function( f ) return function( ]]..params..[[, ... ) return f( ]]..params..", "..args..[[ ) end end ]] return assert( loadstring( code, "=(vararg)" ) )()( f ) end
Use it as follows:
-- two fixed parameters, third parameter holds vararg list local vfunc = vararg( 2, function( a, b, arg ) print( a, b ) for i,v in ipairs( arg ) do print( "", i, v ) end end ) vfunc( "a" ) vfunc( "a", "b" ) vfunc( "a", "b", "c" ) vfunc( "a", "b", "c", "d" )
The interface of the vararg function described above may work even for earlier versions of Lua, but you probably need a separate implementation in a separate file, because the languages ββare too different.