-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathex18.3.lua
More file actions
35 lines (34 loc) · 863 Bytes
/
ex18.3.lua
File metadata and controls
35 lines (34 loc) · 863 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
local function uniquewords (filename)
local f = assert(io.open(filename, "r"))
local line = f:read() -- current line
local pos = 1
local dict = {}
-- current position in the line
return function ()
-- iterator function
while line do
-- repeat while there are lines
local w, e = string.match(line, "(%w+)()", pos)
if w then
-- found a word?
pos = e
-- next position is after this word
if not dict[w] then
dict[w] = true
return w
end
-- return the word
else
line = f:read() -- word not found; try next line
pos = 1
-- restart from first position
end
end
f:close()
return nil
-- no more lines: end of traversal
end
end
for w in uniquewords("test.txt") do
print(w)
end