-- Lua utilities module                  Copyright Mark Colclough, 2007

module(..., package.seeall)

-- grep(filename, pattern, first)  returns match(es) in line(s) of a file
-- pgrep(filename, pattern, first) returns match(es) in line(s) of output
--                                                           from a process
-- If called with first = 1, returns the match(es) of the
-- first matching line as a list. You may get nil.
-- If called with first = nul, returns an array containing one array
-- of match(es) for each matching line. You may get an empty table.

-- resc(str)   returns a string in which any Lua-regex characters are escaped
-- dt1(table)  prints out the keys and values of a table, 1 level deep
-- dt2(table)  prints out the keys and values of a table, 2 levels deep

local function grep2(filename, pattern, first, fil) 
	local results = {}
	local line, result
	
	for line in fil:lines() do
		result = {string.match(line, pattern)}
		if #result > 0 then
			if first then return unpack(result) end
			results[#results+1] = result
		end
	end
	if first then return end
	return results
end

function grep(filename, pattern, first)
	local fil = io.open(filename, "r")
	if fil == nil then error("Cannot read file", 2) end
	return grep2(filename, pattern, first, fil)
end

function pgrep(filename, pattern, first)
	local fil = io.popen(filename, "r")
	if fil == nil then error("Cannot run file", 2) end
	return grep2(filename, pattern, first, fil)
end

function resc(str)
	return (string.gsub(str, "[%(%)%%%+%-%*%?%[%]%^%$]", "%%%1"))
end

function dt1(table)
	local i,j
	for i,j in pairs(table) do print(i,j) end
end

function dt2(table)
	local i,j,k,l
	for i,j in pairs(table) do
		print("== "..i.." ==")
		for k,l in pairs(j) do print(k,l) end
	end
end