一个简单的迭代器示例
--迭代工厂函数
function value(t)
local i = 0;
return
function()
i = i+1;
return t[i];
end;
end;
t = {10,20,30};
iter = value(t);
while true do
local element = iter();
if element == nil then
break;
end;
print("Element: " .. element);
end;
print();
-- 另一种写法
for element in value(t) do
print("Element: " .. element);
end;
2、输出所有单词
function allword()
local line = io.read();
local pos = 1;
return
function()
local s, e = string.find(line, "%w+", pos);
if s then
pos = e + 1;
return string.sub(line, s, e);
end;
end;
end;
for word in allword() do
print(word);
end;
Lua chapter 6
时间: 2024-10-16 10:10:00