18.1
数值型for应该指的是for i=n,m,1的形式,也就是i从n开始按步长1逐渐递增,直到大于m结束循环
function fromto(n,m)
n=n-1
return function ()
n=n+1
if n<=m then
return n
end
end
end
无状态迭代器
#!/usr/bin/lua
local function iter(m,n) --注意m和n的顺序
n=n+1
if n<=m then
return n
end
end
function fromto (n,m)
return iter,m,n-1 --m不可变状态,n控制变量
end
for i in fromto(3,11) do
print(i) --body
end
18.2
增加一个步进的参数
#!/usr/bin/lua
--数值型for应该指的是for i=n,m,k的形式,也就是i从n开始按步长k逐渐递增,直到大于m结束循环
function fromto(n,m,k)
k=k or 1
n=n-k
return function ()
n=n+k
if n<=m then
return n
end
end
end
for i in fromto(2,6,0.5) do
print(i) --body
end
无状态迭代器
#!/usr/bin/lua
local function iter(t,n) --注意m和n的顺序
n=n+t[2]
if n<=t[1] then
return n
end
end
function fromto (n,m,k)
return iter,{m,k},n-k --m不可变状态,n控制变量
end
for i in fromto(3,11,0.5) do
print(i) --body
end
18.3
#!/usr/bin/lua
--所有重复的单词只输出一次,将单词作为键,单词出现的次数作为键值
function uniquewords(file)
local t={}
local pos=1
for line in io.lines(file) do
local w,e=string.match(line,"(%w+)()",pos)
while w do
pos=e
t[w]=t[w]==nil and 1 or t[w]+1
w,e=string.match(line,"(%w+)()",pos)
end
pos=1
end
return next,t,nil
end
18.4
#!/usr/bin/lua
local function iter(str,t) --t[1]是front,t[2]是tail
t[1]=t[1] or 1
t[2]=t[2] or 0
if t[1]<#str then
if t[2]<#str then
t[2]=t[2]+1
else
t[1]=t[1]+1
t[2]=t[1]
end
local substr=string.sub(str,t[1],t[2])
if string.match(substr,"[%S]+") then --当子串全是空白字符时认为是空子串,返回nil
return t,substr
else
return t
end
else
return nil
end
end
function substring(str)
return iter,str,{}
end
----------------------------------------------
for _,s in substring("hel l o") do
if s then
print(s)
end
end
18.5
#!/usr/bin/lua
local function iter(tab,index) --index[1]是front,index[2]是tail
index[1]=index[1] or 1
index[2]=index[2] or 0
local temp={}
if index[1]<#tab then
if index[2]<#tab then
index[2]=index[2]+1
else
index[1]=index[1]+1
index[2]=index[1]
end
for i=index[1],index[2] do
temp[#temp+1]=tab[i]
end
return index,temp
else
return nil
end
end
function subtab(tab)
return iter,tab,{}
end
a={1,2,3,4}
for _,t in subtab(a) do
for k,v in pairs(t) do
print(v)
end
print("-------------")
end
要是集合有空洞或者非数字键应该怎么处理呢