gpt4 book ai didi

lua - 在早期版本的 Lua 中使用可变参数,但希望与 5.2+ 兼容

转载 作者:行者123 更新时间:2023-12-04 14:57:02 25 4
gpt4 key购买 nike

我目前正在编写 Lightroom 插件。 Lightroom 不使用 5.2 版。我有以下功能,目前工作正常,但我担心 Lightroom 确实升级到更新版本,此代码会中断。您对在这种情况下以独立于 lua 版本的方式提供可变参数处理有什么建议吗?

以下代码检查函数 用作表中的键 需求模块 .如果是这样,它会组成一个函数,其中包含一个调用,将模块更改为键 指向的值。女 然后调用函数 F 及其参数。

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

最佳答案

Lua 5.1 及更高版本支持新的可变参数处理方式:

function vfunc( ... )
for i = 1, select( '#', ... )
print( i, (select( i, ... )) )
end
end

或者,如果您真的希望每个函数调用都在新分配的表中使用可变参数(注意 nil 参数):
function vfunc( ... )
local args = {...}
for i, v in ipairs( args ) do
print( i, v )
end
end

如果你还需要支持 Lua 5.0,那你就倒霉了,因为 ...参数列表之外是语法错误。您必须求助于条件代码生成来规避:
-- 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

像这样使用它:
-- 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" )
vararg的接口(interface)上面的函数甚至可以适用于更早版本的 Lua,但您可能需要在单独的文件中单独实现,因为语言差异太大。

关于lua - 在早期版本的 Lua 中使用可变参数,但希望与 5.2+ 兼容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34376466/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com