lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Actually, I found a bug in my prior code submission with the short-hand options all getting the same values, here's the fix. I seem to have hit a small lull in this mailing list's activity, but I'm looking for a yes before I place it on the lua-users wiki. Any suggestions about making it more efficient, or smaller, are very welcome.

-- getopt returns a table where associated keys are true or nil
-- the string options contains the options that have associated values `-b one' style
-- Example: opts["a"]==true, opts["b"]=="one"
function getopt( arg, options )
  local tab = {}
  local count = 1
  options = options or ""
  for k, v in ipairs(arg) do
    if ( string.sub( v, 1, 2) == "--" ) then
      local x = string.find( v, "=", 1, true )
      if ( x ) then tab[ string.sub( v, 3, x-1 ) ] = string.sub( v, x+1 )
      else          tab[ string.sub( v, 3 ) ] = true
      end
    elseif ( string.sub( v, 1, 1 ) == "-" ) then
      local y = 2
      local jopt
      while ( y <= string.len(v) ) do
        jopt = string.sub( v, y, y )
        if ( string.find( options, jopt, 1, true ) ) then
          while true do
            count = count + 1
            if ( count > #arg ) then
              tab[ jopt ] = true
              break
            end
            if string.sub( arg[count], 1, 1) ~= "-" then
              tab[ jopt ] = arg[count]
              break
            end
          end
        else tab[ jopt ] = true
        end
        y = y + 1
      end
    end
  end
  return tab
end

-- Test code
opts = getopt( arg, "ab" );
for k, v in pairs(opts) do
  print( k, v )
end