[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: The wild, whacky, wonderful world of workarounds
- From: Steve Litt <slitt@...>
- Date: Sun, 23 Jan 2011 00:51:30 -0500
:-)
Continue statements? We don't need no steenking continue statements.
Watch this:
The following is the input file:
===========================================
one
two
three
four
five
six
seven
===========================================
The following is the program
===========================================
#!/usr/bin/lua
sf = string.format
Relevant_lines = {}
function Relevant_lines.new(fname)
local self = {}
local handle = assert(io.open(fname, "r"),
"Relevent_lines() Crashed, could not open input file!")
local thisline
local prevline
local prevrelevantline
local thislineno = 0
local prevrelevantlineno = 0
function self.is_relevant(tab)
return(thisline and string.match(thisline, "%S"))
end
function self.next_rline()
prevline = thisline
thisline = handle:read("*line")
thislineno = thislineno + 1
while thisline and not self.is_relevant() do
prevline = thisline
thisline = handle:read("*line")
thislineno = thislineno + 1
end
if thisline then
return thislineno, thisline
else
io.close(handle)
return nil, nil
end
end
function self.set_is_relevant(fcn)
self.is_relevant = fcn
end
function self.newincr() return self.next_rline end
return(self)
end
print("=== PRINTING ONLY NONBLANK LINES ===")
local maker = Relevant_lines.new("test.txt")
for lineno, line in maker.newincr() do
print(sf("%5d: %s", lineno, line))
end
print("=== PRINTING ALL LINES ===")
local maker = Relevant_lines.new("test.txt")
allow_all = function(tab) return true end
maker.set_is_relevant(allow_all)
for lineno, line in maker.newincr() do
print(sf("%5d: %s", lineno, line))
end
===========================================
Here's the output:
===========================================
=== PRINTING ONLY NONBLANK LINES ===
1: one
2: two
4: three
5: four
9: five
10: six
12: seven
=== PRINTING ALL LINES ===
1: one
2: two
3:
4: three
5: four
6:
7:
8:
9: five
10: six
11:
12: seven
slitt@mydesk:~$
===========================================
It is actually kinda cool for a workaround. You can pass in any callback you
want in order to implement any criteria for lines passed through, and it still
keeps track of original line numbers. The fact that you can pass in a table
means you really can implement pretty much any criteria you want. The fact
that tables are passed by reference means your callback could even *write* to
the table.
One addition might be another callback that self.is_relevant() calls on
rejection.
Obviously I didn't write it in a succinct manner nor a Lua-appropriate manner,
but I think you can see what I'm talking about.
SteveT
Steve Litt
Recession Relief Package
http://www.recession-relief.US
Twitter: http://www.twitter.com/stevelitt