Posix Get Opt

lua-users home
wiki

Here is another implementation of getopt in Lua, but been more compliant with the one defined by [POSIX]. Please feel free to improve it.

function getopt(arg, options)
    local opt, optind = {}, 1
    local waiting

    for _,v in ipairs(arg) do
        if waiting then
            -- short option waiting for a value
            opt[waiting] = v
            optind = optind + 1
            waiting = nil
        elseif v == "-" then
            break
        elseif v:sub(1, 1) == "-" then
            optind = optind + 1
            if v == "--" then
                break
            elseif v:sub(1, 2) == "--" then
                -- long option
                local x = v:find("=", 1, true)
                if x then
                    opt[v:sub(3, x-1)] = v:sub(x+1)
                else
                    opt[v:sub(3)] = true
                end
            else
                -- short option
                local j, l = 2, #v
                while (j <= l) do
                    local t = v:sub(j, j)
                    local x = options:find(t, 1, true)
                    if t == ":" then
                        io.stderr:write(arg[0],": invalid option --'", t, "'\n")
                        opt["?"] = true
                    elseif x then
                        if options:sub(x+1, x+1) == ":" then
                            local w = v:sub(j+1)
                            if #w > 0 then
                                opt[t] = w
                                j = l
                            else
                                waiting = t
                            end
                        else
                            opt[t] = true
                        end
                    else
                        io.stderr:write(arg[0],": invalid option --'", t, "'\n")
                        opt["?"] = true
                    end
                    j = j + 1
                end
            end
        else
            break
        end
    end

    if waiting ~= nil then
        io.stderr:write(arg[0],": option requires an argument -- '",waiting,"'\n")
        opt[":"] = true
    end

    return opt, optind
end

See Also


FindPage · RecentChanges · preferences
edit · history
Last edited December 12, 2009 1:46 pm GMT (diff)