Here is an example of what I'm doing to the awks, here is my first
crack at the new "head" utility, and the "getopts" function it uses:
====================================================================
#!/usr/bin/lua -f
function oneFile(file)
if file then
ret , rc = readfrom(file)
if ( not ret ) then
write ( "\n" .. "ERROR: file: "..file.." GOT: "..rc.."\n\n" )
return
end
else
file = "standard input"
end
if headers then
print ( "==> " .. file .. " <==" );
end
if optc then
write( read( optc ) )
else
for i = 1, optn do
print( read("*l") )
end
end
if headers then
print()
end
end
luahome=getenv("LUAHOME")
if not luahome then luahome = "." end
dofile (luahome.."/getopts.lua")
opts,narg,myst=getopts({c=1,n=1,q=0,v=0})
optc = opts["c"]
optn = opts["n"]
if opts["v"] then
headers=1
end
if not optc and not optn then
if myst then
last = strsub (myst,-1)
if last=="b" or last=="k" or last=="m" then
optc = myst
else
optn = myst
end
else
optn = 10
end
end
if optc then
last = strsub( optc, -1)
if last=="b" then
optc = strsub(optc,1,-2)
end
if last=="k" then
optc = strsub(optc,1,-2) * 1024
end
if last=="m" then
optc = strsub(optc,1,-2) * 1048576
end
end
if getargs()[narg] then
if getargs()[narg + 1] then
if not opts["q"] then
headers=1
end
end
repeat
oneFile(getargs()[narg])
narg = next(getargs(), narg)
until narg == "n"
else
oneFile()
end
====================================================================
-- takes a table with (optchar, numargs)
-- returns a table with (optchar, value ("" if none))
-- , index of first non-option argument
-- , the value of the last unknown option ( for things like "head -32" )
-- initially only supports "cut -f 1" or "cut -c 1-7" type args
--
function getopts (optdef)
for a,b in optdef
do
end
local opts={}
local args=getargs()
idx=3
lim=getn(args)
while (args[idx])
do
if args[idx] == "--" then
break
end
if strsub(args[idx],1,1) == "-"
then
curopt = strsub(args[idx],2,2)
if optdef[curopt]
then
if optdef[curopt] > 0
then
-- support for 'cut -f1' here
idx = idx + 1
-- support for 'prog -x asdf qwer' here
opts[curopt] = args[idx]
else
opts[curopt] = ""
-- support for 'rm -rf' type args here
end
else
mysteryopt = strsub(args[idx],2)
end
else
break
end
idx = idx + 1
end
return opts, idx, mysteryopt
end
====================================================================