这是 Lua 中 GetOpt 的替代实现。其目标是在尽可能符合 POSIX 的同时,不依赖任何外部代码。
function getopt( arg, options )
local tab = {}
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 l = string.len(v)
local jopt
while ( y <= l ) do
jopt = string.sub( v, y, y )
if string.find( options, jopt, 1, true ) then
if y < l then
tab[ jopt ] = string.sub( v, y+1 )
y = l
else
tab[ jopt ] = arg[ k + 1 ]
end
else
tab[ jopt ] = true
end
y = y + 1
end
end
end
return tab
end
opts = getopt( arg, "ab" )
for k, v in pairs(opts) do
print( k, v )
end
另请参阅
最近更改 · 偏好设置
编辑 · 历史记录
最后编辑于 2009 年 12 月 12 日凌晨 12:39 GMT (差异)