-- awkward 0.00 -- GCW 29/06/05 -- pseudo_awk interpreter do printf = function (...) print(string.format(unpack(arg))) end -- use as: for i,field in split(text,pat) do ... end split = function (t,p) local pat,n,count,L = "(.-)"..p, 1,0,string.len(t) local f = function (s,v) local i,j,x = string.find(s,pat,n) if i then count = count + 1 n = j + 1 return count,x elseif n < L then count = count + 1 x = string.sub(s,n,-1) n = L + 1 return count,x end -- if end -- function return f,t,n end -- function readfile = function (name) local f = assert(io.open(name,"r"),"Cannot open file") local s = f:read("*all") f:close() return s end -- function local parse = function (fn) local s = "\n"..readfile(fn) local pat = "\n(.-)(%b{})" RULES = {} for p,a in string.gfind(s,pat) do if p == "" then p = "true" end -- if local i,j,x = string.find(p,"^%s*/([^/]+)/%s*$") if i then p = [[string.find($[0],"]]..x..[[") ~= nil]] end if string.find(p,"^%s*BEGIN%s*$") then BEGIN = loadstring(string.sub(a,2,-2)) elseif string.find(p,"^%s*END%s$") then END = loadstring(string.sub(a,2,-2)) else table.insert(RULES,{ pat = loadstring("return "..p); act = loadstring(string.sub(a,2,-2)); }) end -- if end -- for end -- function local awk = function(script,name) parse(script) local s = readfile(name) FILENAME = name if BEGIN then BEGIN() end -- if for $n,$0 in split(s,RS or "\n") do $,NR = {},$n $[0] = $0 for i,field in split($0,FS or "%s+") do table.insert($,field) end -- for NF = table.getn($) for _,x in ipairs(RULES) do if x.pat() then x.act() end -- if end -- for end -- for if END then END() end -- if end -- function awk(arg[1],arg[2]) end -- do