'How to filter a Lua array inplace?

How to filter a Lua array inplace?

For example, having an array of { 1, 5, 7 } and a function function(elem) return elem > 1 end, the inplace filtering function should change the array to { 5, 7 }. It is also desired not to break ipairs iteration on the array, so the array should still start with index 1.

By "array" I mean the part of a Lua table that starts with key 1 and goes through consecutive integer keys until it finds a nil. The same thing you iterate with ipairs.

lua


Solution 1:[1]

The following function solves the problem:

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

Solution 2:[2]

function filter_inplace(t, val, func)
   for k, v in ipairs(t) do
       if v = val then
       table.remove(t,k)
       func(t, val, filter_inplace)
       end
    end
end

filter_inplace(t, 1, filter_inplace)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 VasiliNovikov
Solution 2 ???? ????-??