Lua - 过滤迭代器
过滤函数是一种当被调用时根据给定条件返回过滤结果的函数。在 Lua 中,我们可以轻松定义一个过滤迭代器。
编写过滤函数
首先让我们创建一个通用的过滤函数,它可以接受一个数组和一个过滤迭代器。
-- 使用过滤迭代器定义过滤函数
table.filter = function(array, filterIterator)
-- 要返回的过滤结果
local result = {}
-- 遍历主数组
for key, value in pairs(array) do
-- 调用 filterIterator
if filterIterator(value, key, array) then
-- 将值添加到过滤结果中
table.insert(result,value)
end
end
-- 返回过滤结果
return result
end
解释
我们创建了一个名为 table.filter 的函数。
这个函数接受一个数组和一个迭代器函数。
在函数中,我们使用 for 循环,然后调用迭代器来过滤相应的值。
如果 filterIterator 返回 true,则将值存储到结果数组中。
最后返回结果数组作为过滤后的输出。
调用过滤函数来过滤数组
在调用过滤函数时,我们传递一个迭代器函数,用于检查数字是否为偶数。
-- 源数组
array = {1, 2, 3, 4, 5, 6, 7, 8, 9}
-- 使用偶数过滤器调用过滤函数
filteredArray = table.filter(array,
-- 偶数过滤器
function(element, key, index)
return element % 2 == 0
end
)
打印过滤后的数组
for key,value in ipairs(filteredArray) do print(key,value) end
使用迭代器的完整示例
以下示例展示了如何使用迭代器从列表中过滤出奇数。
main.lua
-- 使用过滤迭代器定义过滤函数
table.filter = function(array, filterIterator)
-- 要返回的过滤结果
local result = {}
-- 遍历主数组
for key, value in pairs(array) do
-- 调用 filterIterator
if filterIterator(value, key, array) then
-- 将值添加到过滤结果中
table.insert(result,value)
end
end
-- 返回过滤结果
return result
end
-- 源数组
array = {1, 2, 3, 4, 5, 6, 7, 8, 9}
-- 使用偶数过滤器调用过滤函数
filteredArray = table.filter(array,
-- 偶数过滤器
function(element, key, index)
return element % 2 == 0
end
)
for key,value in ipairs(filteredArray) do
print(key,value)
end
输出
当上述代码构建并执行时,会产生以下结果 −
1 2 2 4 3 6 4 8