Using varargs in an earlier version of Lua, but requires compatibility with 5.2+

I am currently encoding the Lightroom plugin. Lightroom does not use version 5.2. I have the following function that works fine now, but I am worried that Lightroom is updating to a newer version, this code will break. Do you have any suggestions for making varargs handling independent of the lua version in this case?

The following code checks if the F function is used as the key in the needsModule table. If so, he creates a function that includes a call to change the modules to the value indicated by the F key, followed by a call to the F function and its arguments.

local function wrapFOM(F,...) local openModule = needsModule[F] if openModule == nil then return function() return F(unpack(arg)) end end return function() if LrApplicationView.getCurrentModuleName() ~= openModule then LrApplicationView.switchToModule(openModule) end return F(unpack(arg)) --proper tail call end end 
+6
source share
2 answers

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.

+3
source

According to the Lightroom SDK 4 Programmer's Guide (PDF) :

Lightroom 4 uses version 5.1.4 of the Lua language.

Since Lua 5.1 supports both the old style and the new varargs style, I think you can just use the new style and not worry about advanced compatibility.

+3
source

All Articles