copy:http://blog.csdn.net/phenix32/article/details/8961592
--[[
时间:2013年5月22日11:25:40
作者:PhoenixCao
内容:Lua程序练习3
--]]
-- 闭包示例
names = {"Peter","Phoenix","Mary"}
grades = {Mary = 10, Peter = 7, Phoenix = 8}
table.sort(names,function (n1,n2)
return grades[n1] > grades[n2]
end)
for i = 1, #names do
print(names[i])
end
--[[ 输出结果
Mary
Phoenix
Peter
--]]
-- 闭包是对值的理解,不是函数
function newCounter()
local i = 0
return function() -- 匿名函数
i = i + 1
return i
end
end
c1 = newCounter()
c2 = newCounter()
print(c1) -- 函数指针的所在地址
print(c1()) -- 函数的返回值
print(c1())
print(c2())
--[[ 输出结果
function: 0041C060
1
2
1
--]]
-- 迭代器测试
function list_iter(tbl)
local i = 0
local n = table.getn(tbl)
return function()
i = i + 1
if i <= n then return tbl[i] end
end
end
t = {10,20,30}
iter = list_iter(t)
while true do
local element = iter() -- 调用其函数
if element == nil then break end
print(element)
end
for element in list_iter(t) do
print(element)
end
--[[ 输出结果
10
20
30
10
20
30
--]]
--[[
function allwords()
local line = io.read()
local pos = 1
return function()
while line do
local s,e = string.find(line,"%w+",pos)
if s then -- 找到了起始位置
pos = e + 1
return string.sub(line,s,e)
else -- 没找到接着找下一行,从头开始
line = io.read()
pos = 1
end
end
return nil -- 文件查找结束
end
end
for word in allwords() do
print(word)
end
--]]
--[[ 输入lala la l
输出结果
lala
la
l
--]]
-- 我们要尽量使用无状态的迭代器,因为这样循环的时候由for来保存,
-- 无需要创建对象,花费的代价小,如果不能用无状态的迭代器实现,
-- 应尽可能使用闭包,尽少使用table,因为闭包的代价比创建table要小,
-- 闭包处理速度也比table要快,还可以使用协同来创建迭代器方式。
--(注意:对于for结构来说,状态常量没有用处,仅仅在初始化时获取他的值并传递给迭代函数)
function iter (a, i)
i = i + 1
local v = a[i]
if v then
return i, v --迭代函数返回2个值 索引与值
end
end
function ipairs (a) --ipairs lua简单实现
return iter, a, 0 --返回3个值 迭代函数,状态常量a,控制变量初始值0
end
a = {"one", "two", "three"}
--无状态的迭代器是指不保留任何状态的迭代器,不访问外部函数变量
--因此在循环中我们可以利用无状态迭代器避免创建闭包花费额外的代价。
for i, v in ipairs(a) do --无状态迭代? 完成迭代功能的是for语句
print(i, v)
end
--[[ 输出结果
1 one
2 two
3 three
--]]