我有一个定义为C绑定的函数,该函数提供了通用的for
迭代器:
for el in doc:each() do ... end
我想在Lua中编写一个使用此函数进行迭代的迭代器,但返回每个结果的修改。我怎样才能做到这一点?
编辑:我确定我的迭代器必须启动这样的事情,但我迷失在函数的主体中。
function myiterator()
local f, c, v = doc:each()
return (function(c2, v2)
-- ??
end), ??, ??
end
function myiterator()
local generator, state, prev_x = doc:each()
local function my_generator()
local x, y = generator(state, prev_x)
if x ~= nil then
prev_x = x
-- modify x, y
local modified_x = x + 100
local modified_y = "("..y..")"
-- modified_x must be non-nil
return modified_x, modified_y
end
end
return my_generator
end
之前:
local doc = {each = function() return ipairs{"aa", "bb", "cc"} end}
for x, y in doc:each() do
print(x, y)
end
输出:
1 aa
2 bb
3 cc
后:
local doc = {each = function() return ipairs{"aa", "bb", "cc"} end}
-- insert myiterator definition here
for x, y in myiterator() do
print(x, y) -- now x and y are modified
end
输出:
101 (aa)
102 (bb)
103 (cc)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句