From 8bc02caae600cc3bd21cca42f6749f87cc6afa5f Mon Sep 17 00:00:00 2001 From: mpeterv Date: Thu, 20 Feb 2014 12:34:02 +0400 Subject: [PATCH] Convert can now be a table used as mapping --- spec/convert_spec.lua | 16 ++++++++++++++++ src/argparse.lua | 9 ++++++++- 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/spec/convert_spec.lua b/spec/convert_spec.lua index 4fdb80b..befd767 100644 --- a/spec/convert_spec.lua +++ b/spec/convert_spec.lua @@ -12,6 +12,22 @@ describe("tests related to converters", function() assert.same({numbers = {1, 2, 500}}, args) end) + it("converts arguments using mapping", function() + local choice = { + foo = 1, + bar = 2 + } + + local parser = Parser() + parser:argument "choice" { + convert = choice, + args = "+" + } + + local args = parser:parse{"foo", "bar"} + assert.same({choice = {1, 2}}, args) + end) + it("accepts false", function() local function toboolean(x) if x == "true" then diff --git a/src/argparse.lua b/src/argparse.lua index 25c7cb8..e43379f 100644 --- a/src/argparse.lua +++ b/src/argparse.lua @@ -508,7 +508,14 @@ function Parser:_parse(args, errhandler) local function convert(element, data) if element._convert then - local ok, err = element._convert(data) + local ok, err + + if type(element._convert) == "function" then + ok, err = element._convert(data) + else + ok, err = element._convert[data] + end + assert_(ok ~= nil, "%s", err or "malformed argument '" .. data .. "'") data = ok end