argparse:具有多个参数的选项的转换器函数?
argparse: Converter Function for Option with Multiple Parameters?
我想对一个选项的参数应用不同的转换函数。
考虑以下代码:
parser:option('-c --circle')
:argname{'<radius>', '<coordinates>'}
-- does not work like this:
-- :convert{['<radius>']=tonumber, ['<coordinates>']=tocoords}
:default{1, {0,0}}
:args(2)
:count '0-1'
如您所见,该程序有一个选项 -c
,它有两个参数:radius
和 coordinates
。我想分别应用于不同的转换函数(tonumber
和 tocoords
)。正在阅读 the documentation 我不知道该怎么做。
这可能吗?如果可以,那么正确的设置方法是什么?
如果您认为 Lua Argparse 系统不允许您指定多个函数来将参数转换为特定选项是正确的,那么仍然有办法做到这一点。毕竟,Argparse 必须为每个参数调用一次转换函数。并且没有规定转换函数必须为每次调用做同样的事情。您唯一没有的信息是调用它的特定参数。
所以……作弊。通过使用 Lua 的 first-class 函数创建该信息(注意:以下使用 Lua 5.3):
local function multi_arg_parser(...)
local index = 0
local funcs = table.pack(...)
return function(...)
index = index + 1
return funcs[index](...)
end
end
parser:option('-c --circle')
:argname{'<radius>', '<coordinates>'}
:convert(multi_arg_parser(tonumber, tocoords))
:default{1, {0,0}}
:args(2)
:count '0-1'
这将有效提供 Argparse 将为每个参数调用 convert
函数一次 和 调用 convert
按照它们在命令行中出现的顺序在参数上。 Argparse 几乎肯定不能保证这一点,但这是一个合理的假设。
自 argparse 0.6.0 起有效:
:convert{tonumber, tocoords}
If convert property of an element is an array of functions, they will be used as converters for corresponding arguments in case the element accepts multiple arguments.
我建议使用 Lapp Framework. It supports conversions via a converter method passed to the add_type 方法。此外,它还具有其他方便的功能,例如断言和默认值。
我想对一个选项的参数应用不同的转换函数。
考虑以下代码:
parser:option('-c --circle')
:argname{'<radius>', '<coordinates>'}
-- does not work like this:
-- :convert{['<radius>']=tonumber, ['<coordinates>']=tocoords}
:default{1, {0,0}}
:args(2)
:count '0-1'
如您所见,该程序有一个选项 -c
,它有两个参数:radius
和 coordinates
。我想分别应用于不同的转换函数(tonumber
和 tocoords
)。正在阅读 the documentation 我不知道该怎么做。
这可能吗?如果可以,那么正确的设置方法是什么?
如果您认为 Lua Argparse 系统不允许您指定多个函数来将参数转换为特定选项是正确的,那么仍然有办法做到这一点。毕竟,Argparse 必须为每个参数调用一次转换函数。并且没有规定转换函数必须为每次调用做同样的事情。您唯一没有的信息是调用它的特定参数。
所以……作弊。通过使用 Lua 的 first-class 函数创建该信息(注意:以下使用 Lua 5.3):
local function multi_arg_parser(...)
local index = 0
local funcs = table.pack(...)
return function(...)
index = index + 1
return funcs[index](...)
end
end
parser:option('-c --circle')
:argname{'<radius>', '<coordinates>'}
:convert(multi_arg_parser(tonumber, tocoords))
:default{1, {0,0}}
:args(2)
:count '0-1'
这将有效提供 Argparse 将为每个参数调用 convert
函数一次 和 调用 convert
按照它们在命令行中出现的顺序在参数上。 Argparse 几乎肯定不能保证这一点,但这是一个合理的假设。
自 argparse 0.6.0 起有效:
:convert{tonumber, tocoords}
If convert property of an element is an array of functions, they will be used as converters for corresponding arguments in case the element accepts multiple arguments.
我建议使用 Lapp Framework. It supports conversions via a converter method passed to the add_type 方法。此外,它还具有其他方便的功能,例如断言和默认值。