Download code

Jump to: navigation, search

Back to Word_count_(Lua)

Download for Windows: single file, zip

Download for UNIX: single file, zip, tar.gz, tar.bz2

wc.lua

 1 #!/usr/bin/env lua
 2 -- The authors of this work have released all rights to it and placed it
 3 -- in the public domain under the Creative Commons CC0 1.0 waiver
 4 -- (http://creativecommons.org/publicdomain/zero/1.0/).
 5 -- 
 6 -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 7 -- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 8 -- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 9 -- IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
10 -- CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
11 -- TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
12 -- SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
13 -- 
14 -- Retrieved from: http://en.literateprograms.org/Word_count_(Lua)?oldid=10564
15 
16 
17 tot_chars=0
18 tot_words=0
19 tot_lines=0
20 opts=""
21 
22 function printwc(lines, words, chars, fname)
23 	if(string.find(opts, "l")) then io.write(string.format("% 8d", lines)) end
24 	if(string.find(opts, "w")) then io.write(string.format("% 8d", words)) end
25 	if(string.find(opts, "c")) then io.write(string.format("% 8d", chars)) end
26 	
27 	if(fname~="-") then io.write(" "); print(fname)
28 	else print() end
29 end
30 
31 function wc(fname)
32 	chars=0
33 	words=0
34 	lines=0
35 	
36 	if(fname=="-") then it=io.lines()
37 	else it=io.lines(fname) end
38 
39 	for line in it do
40 		lines=lines+1
41 		for word in string.gfind(line, "[^%s]+") do words=words+1 end
42 		chars=chars+string.len(line)+1
43 	end
44 	printwc(lines, words, chars, fname)
45 
46 	tot_chars=tot_chars+chars
47 	tot_words=tot_words+words
48 	tot_lines=tot_lines+lines
49 end
50 
51 
52 
53 nfiles=0
54 
55 for i=1,table.getn(arg) do 
56 	if(nfiles==0 and string.sub(arg[i], 1, 1)=='-') then
57 		opts=opts .. arg[i]
58 	else
59 		if(string.len(opts)==0) then opts="lwc" end
60 		wc(arg[i])
61 		nfiles=nfiles+1
62 	end
63 end
64 
65 
66 if(string.len(opts)==0) then opts="lwc" end
67 if nfiles<1 then wc("-") end
68 if nfiles>1 then printwc(tot_lines, tot_words, tot_chars, "total") end
69 


hijacker
hijacker
hijacker
hijacker