diff options
author | Ronan Collobert <ronan@collobert.com> | 2014-03-11 19:29:43 +0400 |
---|---|---|
committer | Ronan Collobert <ronan@collobert.com> | 2014-03-11 19:29:43 +0400 |
commit | 6c963b88b03caa48a3195705063b27bbbdbd4446 (patch) | |
tree | 135b01f6439cd584c68b960db9512bf21b7330e7 | |
parent | a6ef0ffe61ae71445edd050fbc6b41c4a3633605 (diff) |
added support for global "call" option
-rw-r--r-- | README.md | 26 | ||||
-rw-r--r-- | init.lua | 22 |
2 files changed, 41 insertions, 7 deletions
@@ -397,6 +397,32 @@ false arguments: } ``` +#### Function call + +In case of success, the argument checker can call a function if +needed. Some users might find it more convenient than calling the argument +checker inside the function of interest. Taking back the first example, one +could use the `call` option and rewrite it as: +```lua +addfive = argcheck{ + {name="x", type="number"}, + + call = function(x) + print(string.format('%f + 5 = %f', x, x+5)) + end +} + +> addfive(5) +5.000000 + 5 = 10.000000 + +> addfive() +stdin:1: arguments: +{ + x = number -- +} +``` + + #### Debug Adding `debug=true` as global option will simply dump the corresponding code @@ -201,6 +201,9 @@ local function argcheck(rules) -- upvalues table.insert(txt, 'local isoftype') table.insert(txt, 'local usage') + if rules.call then + table.insert(txt, 'local call') + end for ridx, rule in ipairs(rules) do if rule.default or rule.defaultf then table.insert(txt, string.format('local arg%dd', ridx)) @@ -226,14 +229,15 @@ local function argcheck(rules) table.insert(ret, string.format('arg%d', ridx)) end end + ret = table.concat(ret, ', ') if rules.pack then - ret = table.concat(ret, ', ') - ret = (rules.quiet and 'true, ' or '') .. '{' .. ret .. '}' - elseif rules.quiet then - table.insert(ret, 1, 'true') - ret = table.concat(ret, ', ') - else - ret = table.concat(ret, ', ') + ret = '{' .. ret .. '}' + end + if rules.call then + ret = 'call(' .. ret .. ')' + end + if rules.quiet then + ret = 'true' .. (#ret > 0 and ', ' or '') .. ret end table.insert(txt, ' local narg = select("#", ...)') @@ -286,6 +290,10 @@ local function argcheck(rules) debug.setupvalue(func, upvalue2idx(func, 'usage'), generateusage(rules)) + if rules.call then + debug.setupvalue(func, upvalue2idx(func, 'call'), rules.call) + end + return func end |