mirror of
https://github.com/TangentFoxy/argparse.git
synced 2025-07-28 11:02:20 +00:00
Allow using separate converters for each argument
When converting an argument in a position, if there is a function in the same position in provided converer array, use it as a converter function. This allows using an array of functions as the value of `convert` property, with each function applied to corresponding argument of a multi-argument option. Ref #14.
This commit is contained in:
@@ -13,6 +13,24 @@ describe("tests related to converters", function()
|
|||||||
assert.same({numbers = {1, 2, 500}}, args)
|
assert.same({numbers = {1, 2, 500}}, args)
|
||||||
end)
|
end)
|
||||||
|
|
||||||
|
it("accepts an array of converters", function()
|
||||||
|
local function tocoords(str)
|
||||||
|
local x, y = str:match("^([^,]*),([^,]*)$")
|
||||||
|
x = tonumber(x)
|
||||||
|
y = tonumber(y)
|
||||||
|
return x and y and {x, y}
|
||||||
|
end
|
||||||
|
|
||||||
|
local parser = Parser()
|
||||||
|
parser:option "-c --circle" {
|
||||||
|
convert = {tonumber, tocoords},
|
||||||
|
args = 2
|
||||||
|
}
|
||||||
|
|
||||||
|
local args = parser:parse{"-c", "123", "456,567"}
|
||||||
|
assert.same({circle = {123, {456, 567}}}, args)
|
||||||
|
end)
|
||||||
|
|
||||||
it("converts arguments using mapping", function()
|
it("converts arguments using mapping", function()
|
||||||
local choice = {
|
local choice = {
|
||||||
foo = 1,
|
foo = 1,
|
||||||
|
@@ -781,7 +781,7 @@ function ElementState:error(fmt, ...)
|
|||||||
self.state:error(fmt, ...)
|
self.state:error(fmt, ...)
|
||||||
end
|
end
|
||||||
|
|
||||||
function ElementState:convert(argument)
|
function ElementState:convert(argument, index)
|
||||||
local converter = self.element._convert
|
local converter = self.element._convert
|
||||||
|
|
||||||
if converter then
|
if converter then
|
||||||
@@ -789,6 +789,8 @@ function ElementState:convert(argument)
|
|||||||
|
|
||||||
if type(converter) == "function" then
|
if type(converter) == "function" then
|
||||||
ok, err = converter(argument)
|
ok, err = converter(argument)
|
||||||
|
elseif type(converter[index]) == "function" then
|
||||||
|
ok, err = converter[index](argument)
|
||||||
else
|
else
|
||||||
ok = converter[argument]
|
ok = converter[argument]
|
||||||
end
|
end
|
||||||
@@ -844,7 +846,7 @@ function ElementState:invoke(alias)
|
|||||||
end
|
end
|
||||||
|
|
||||||
function ElementState:pass(argument)
|
function ElementState:pass(argument)
|
||||||
argument = self:convert(argument)
|
argument = self:convert(argument, #self.args + 1)
|
||||||
table.insert(self.args, argument)
|
table.insert(self.args, argument)
|
||||||
|
|
||||||
if #self.args >= self.element._maxargs then
|
if #self.args >= self.element._maxargs then
|
||||||
|
Reference in New Issue
Block a user