如何在 Lua 数组中原地过滤?

如何在 Lua 数组中原地过滤?

例如,有一个数组{1,5,7}和一个函数function(elem) return elem>1 end,原地过滤函数应该将数组更改为{5,7}。还希望不破坏对数组的‘ipairs’迭代,因此数组应该仍然以索引1开头。

所谓“数组”,是指从键1开始遍历并一直到找到一个空值的 Lua 表的部分。与您使用 ipairs 迭代的相同内容。

点赞
用户1091436
用户1091436

下面的函数解决了这个问题:

function filter_inplace(arr, func)
    local new_index = 1
    local size_orig = #arr
    for old_index, v in ipairs(arr) do
        if func(v, old_index) then
            arr[new_index] = v
            new_index = new_index + 1
        end
    end
    for i = new_index, size_orig do arr[i] = nil end
end
2018-04-07 17:23:51
用户12914472
用户12914472

由于在迭代时更改索引,建议使用 while 循环。

function filterInplace(t, func)
    local i = 1
    while (i <= #t) do
        if func(t[i]) then
            -- 值符合条件
            i = i + 1
        else
            table.remove(t, i)
        end
    end
end
2023-01-05 01:05:57