lua-users home
lua-l archive

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


Wim Couwenberg wrote:
Happy new year to everyone!

From me too :-D

Here is my contribution (I should write with plural...) to the Type "file" test case.

I give three versions, from the shortest I could make to one more respectful of the requirements (splitting too long lines).

I have put all three versions in the same file, to avoid sending too much files... Just change the first assignment to "S", "SC" or "L".

--
Philippe Lhoste
--  (near) Paris -- France
--  http://Phi.Lho.free.fr
--  --  --  --  --  --  --  --  --  --  --  --  --  --
#!Lua-5.0.exe
-- APLC Type File.
-- http://www.kochandreas.com/home/language/tests/TYPE.HTM
-- by Philippe Lhoste <PhiLho(a)GMX.net> http://Phi.Lho.free.fr
-- v. 1.0 -- 2005/01/01

local choice = 'L' -- Three programs in one, to avoid sending three files...

if choice == 'S' then
	-- Shortest (or close...).
	-- Quick and dirty: no error checking on argument validity or file existence or rights.
	-- Lets system close the file upon program completion.
	print((io.open(arg[1])):read"*a")

elseif choice == 'SC' then
	-- Short but clean... Slightly more readable too.
	local f = assert(io.open(arg[1] or ''), "Cannot open " .. (arg[1] or "(No file given)"))
	print(f:read"*a")
	f:close()

else
	-- Line by line.
	-- More suited to large files as the two above read the whole file before printing it.
	-- Could handle usage, stdin, better error management,
	-- but that's beyond this test case.
	local bSplit, splitPos, splitPattern = false, 79, ''
	local param, filename = arg[1] or '', ''
	-- Check if a split option has been given
	if string.sub(param, 1, 2) == '-s' then
		bSplit = true
		-- With a split value?
		if string.sub(param, 3) ~= '' then
			splitPos = tonumber(string.sub(param, 3)) or splitPos -- Should test > 0
		end
		-- Match number of characters
		splitPattern = '(' .. string.rep('.', splitPos) .. ')'
		filename = arg[2]
	else
		filename = arg[1]
	end
	local f = assert(io.open(filename or ''), "Cannot open " .. (filename or "(No file given)"))
	for line in f:lines() do
		-- Avoid overflows from tab expansion. May be user defined...
		line = string.gsub(line, '\t', ' ')
		-- Split line at given length, if asked
		if bSplit then
			line = string.gsub(line, splitPattern, "%1\n")
		end
		io.write(line .. '\n') -- Should avoid \n\n if splitted...
	end
end