lua-users home
lua-l archive

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


Hi,

Below is my sort2 entry for Lua 5.0.2 (submitted). It writes to an arbitrary file or stdout (if not provided).

--
Wim


if not arg[1] then
	print(arg[0] .. [[ infile [outfile]
sort lines from infile to outfile or to stdout if no outfile is provided.]])
	return
end

local infile, err = io.open(arg[1], "r")
if not infile then
	io.stderr:write(err, "\n")
	return
end

local outfile
if arg[2] then
	outfile, err = io.open(arg[2], "w")
	if not outfile then
		infile:close()
		io.stderr:write(err, "\n")
		return
	end
end

local lines = {}

for line in infile:lines() do
	table.insert(lines, line)
end

infile:close()

table.sort(lines)

for _, line in ipairs(lines) do
	(outfile or io.stdout):write(line, "\n")
end

if outfile then
	outfile:close()
end