How to Parse command-Line arguments?
There is no standard way to do this (which should come as no surprise), so packages tend to roll their own. However, the task is not hard using Lua string matching. Here is how LuaRocks parses its arguments:
--- Extract flags from an arguments list.
-- Given string arguments, extract flag arguments into a flags set.
-- For example, given "foo", "--tux=beep", "--bla", "bar", "--baz",
-- it would return the following:
-- {["bla"] = true, ["tux"] = "beep", ["baz"] = true}, "foo", "bar".
function parse_flags(...)
local args = {...}
local flags = {}
for i = #args, 1, -1 do
local flag = args[i]:match("^%-%-(.*)")
if flag then
local var,val = flag:match("([a-z_%-]*)=(.*)")
if val then
flags[var] = val
else
flags[flag] = true
end
table.remove(args, i)
end
end
return flags, unpack(args)
end
Lapp provides a higher-level solution. It starts from the fact that you have to print out a usage string if you expect your script to be used by others. So, why not encode each allowable flag (with its type) in the usage string itself?
-- scale.lua
require 'lapp'
local args = lapp [[
Does some calculations
-o,--offset (default 0.0) Offset to add to scaled number
-s,--scale (number) Scaling factor
<number> (number ) Number to be scaled
]]
print(args.offset + args.scale * args.number)
Since the flags are declared as being numerical values, this very small script has fairly robust error checking:
D:\dev\lua\lapp>lua scale.lua
scale.lua:missing required parameter: scale
Does some calculations
-o,--offset (default 0.0) Offset to add to scaled number
-s,--scale (number) Scaling factor
<number> (number ) Number to be scaled D:\dev\lua\lapp>lua scale.lua -s 2.2 10
22
D:\dev\lua\lapp>lua scale.lua -s 2.2 x10
scale.lua:unable to convert to number: x10
...